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?
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?
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]
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.
$string = preg_replace("(windows( xp)?)", "<em>$0</em>", $string)