0

Here is my problem:

Using preg_replace('@\b(word)\b@','****',$text);

Where in text I have word\word and word, the preg_replace above replaces both word\word and word so my resulting string is ***\word and ***.

I want my string to look like : word\word and ***.

Is this possible? What am I doing wrong???

LATER EDIT

I have an array with urls, I foreach that array and preg_replace the text where url is found, but it's not working.

For instance, I have http://www.link.com and http://www.link.com/something

If I have http://www.link.com it also replaces http://www.link.com/something.

4

3 回答 3

3

You are effectively specifying that you don't want certain characters to count as word boundary. Therefore you need to specify the "boundaries" yourself, something like this:

preg_replace('@(^|[^\w\\])(word)([^\w\\]|$)@','**',$text);

What this does is searches for the word surrounded by line boundaries or non-word characters except the back slash \. Therefore it will match .word, but not .word\ and not `\word. If you need to exclude other characters from matching, just add them inside the brackets.

于 2012-11-01T10:11:38.943 回答
0

You could just use str_replace("word\word", "word\word and"), I dont really see why you would need to use a preg_replace in your case given above.

于 2012-11-01T10:07:38.927 回答
0

Here is a simple solution that doesn't use a regex. It will ONLY replace single occurances of 'word' where it is a lone word.

<?php
$text = "word\word word cat dog";
$new_text = "";
$words = explode(" ",$text); // split the string into seperate 'words'

$inc = 0; // loop counter
foreach($words as $word){

    if($word == "word"){ // if the current word in the array of words matches the criteria, replace it
        $words[$inc] = "***";
    }
    $new_text.= $words[$inc]." ";
    $inc ++;
}

echo $new_text; // gives 'word\word *** cat dog'
?>
于 2012-11-01T10:25:01.313 回答