tags:

views:

79

answers:

3

how write the script, which menchion the whole word, if it contain the keyword? example: keyword "fun", string - the bird is funny, result - the bird is * funny*. i do the following

     $str = "my bird is funny";
     $keyword = "fun";
     $str = preg_replace("/($keyword)/i","<b>$1</b>",$str);

but it menshions only keyword. my bird is *fun*ny

+1  A: 

You can do the following:

 $str = preg_replace("/\b([a-z]*${keyword}[a-z]*)\b/i","<b>$1</b>",$str);

Example:

$str = "Its fun to be funny and unfunny";
$keyword = 'fun';
$str = preg_replace("/\b([a-z]*${keyword}[a-z]*)\b/i","<b>$1</b>",$str);
echo "$str"; // prints 'Its <b>fun</b> to be <b>funny</b> and <b>unfunny</b>'
codaddict
@codaddict i know, that in regular-expressions $ means the end of something.but what does it mean in your script? and why { simbols, instead of (?
Syom
@Syom: This is only for PHP to distinguish between variables and literal string content in double quoted string declarations: `"$foobar"` will be evaluated to the value of `$foobar` while `"($foo}bar"`/`"${foo}bar"` will be evaluated to the value of `$foo` concatenated with `bar`. See http://php.net/manual/en/language.types.string.php#language.types.string.parsing for further information.
Gumbo
+3  A: 

Try this:

preg_replace("/\w*?$keyword\w*/i", "<b>$0</b>", $str)

\w*? matches any word characters before the keyword (as least as possible) and \w* any word characters after the keyword.

And I recommend you to use preg_quote to escape the keyword:

preg_replace("/\w*?".preg_quote($keyword)."\w*/i", "<b>$0</b>", $str)
Gumbo
congratulations , it works. thanks
Syom
+1. It works and fast answer. Why the ? in the pattern?
sberry2A
@sberry2A: PCRE regular expressions are greedy by default. That means a quantifier is expanded to the maximum of possible repetition. The `?` is making the quantifier ungreedy so it matches as least repetitions as possible. (See also http://www.regular-expressions.info/repeat.html)
Gumbo
A: 

Basically the same thing as Gumbo.

preg_replace("/\w*{$keyword}\w*/i", "<b>$0</b>", $str);
sberry2A