tags:

views:

64

answers:

3

im new to preg and wants to find some strings i got in an array and emphasize each one.

eg.

  array[0] = "windows";
  array[0] = "windows xp";

  text will be: <em>windows</em> is bla bla...<em>windows xp</em> is bla bla

how could i do that?

+3  A: 

Very simple replacement, no need for preg_*:

$mytest = "Windows XP was all right, but I like Windows 7 better!°";
$replacement = "Windows XP";
echo str_replace($replacement, "<em>".$replacement."</em>", $mytest);

You can also replace arrays. [Manual entry][1]

Pekka
sorry i have updated the question.
weng
an answer is the same ;-)even for updated question
UncleMiF
$string = 'windows xp';$string = '<em>' . $string . '</em>';echo $string;
UncleMiF
see my updated question. i forgot to use code mode=)
weng
Updated my answer.
Pekka
im sorry. ive updated my question cause i noticed that i wanted to find multiplie strings in an array rather than just replace one.
weng
Updated my answer.
Pekka
But if it's HTML you're replacing in, better update your question. There are a lot of intricacies to that.
Pekka
+1  A: 

If you're doing the search and replace on text, this is easy:

$text = 'windows xp';
$input = '....';
$output = str_replace($text, '<em>' . $text . '</em>', $input);

If you have a block of HTML stored as a string there is another issue to consider: what if the text the user searches for is part of a tag or attribute name or value? If you want to highlight "strong" you don't want to replace this:

<strong>some text</strong>

with:

<<em>strong</em>>some text</<em>strong</em>>

as your markup will no longer be valid.

That is the problem with using simple search and replace or regular expressions on markup. The best way of handling this is to convert to markup into a DOM tree and then walk it doing replacements on text nodes. Even that has issues. If you want to highlight "windows xp" do you want to highlight this case:

windows <i>xp</i>

To th euse it appears as "windows xp" so it's reasonable to assume the user will want to highlight that.

cletus
i want to search a text for keywords i've got in an array and hightlight them all. i looks like there are a lot of things to consider so i dont run intp problem with html tags. see my updated post..
weng
A: 
$string = preg_replace("(windows( xp)?)", "<em>$0</em>", $string)
Brian Campbell