1

preg_replace only replace once time? i am tring to remoe unwanted words from a sentence, why in this situation, "an" hasn't been replaced?

http://www.php.net/manual/en/reference.pcre.pattern.modifiers.php

in modifier part, what should i set?

$items = "This is an apple... ";
echo preg_replace('/ an | is /i',' ',$items);
//This an apple...   

I need return "This apple...", thanx.

4

2 回答 2

3

Put it in parenthesises and surround it with word boundaries (\b):

$items = "This is an apple... ";
echo preg_replace('/\b(an|is)\b/i', ' ', $items);
//This     apple

You can remove extra spaces, by using the following:

$items = "This is an apple... ";
echo trim(preg_replace(array('/\b(an|is)\b/i', '/[ ]+/'), ' ', $items));
//                                              ^^^^^^
//This apple

Another example with the same code:

$items = "An apple, this is";
echo trim(preg_replace(array('/\b(an|is)\b/i', '/[ ]+/'), ' ', $items));
//apple, this
于 2013-04-25T19:10:27.783 回答
0

As commented by @Mark B your regex is not giving expected result because first replacement is happening for [space]is[space] and that removes the trailing space from the the next match [space]an[space] and hence you get This an apple....

Here is the correct way to use preg_replace in your case using lookahead and lookbehind:

$items = "This is an apple... ";
echo '[' . preg_replace('/ *(?<= )(an|is)(?= ) */i', ' ', $items) . "]\n";
// OUTPUT: [This  apple... ]
于 2013-04-25T19:54:45.393 回答