you must put pattern delimiters at the begining and at the end of the pattern, example:
$pattern = '#class="(.+)"(.+)<a.+>(.+)</a>#';
Here #
is a better choice than /
because you avoid to escape all the slashes inside your pattern, but you can write:
$pattern = '/class="(.+)"(.+)<a.+>(.+)<\/a>/';
As an aside comment, your pattern will cause many backtracks:
$pattern = '~class="([^"]+)"([^>]*>)<a[^>]+>([^<]+)</a>~';
will work better.
Keep in mind that +
and *
are by default greedy quantifiers (i.e. they take all they can).
If I use a restricted character class instead of the dot, I can stop the greediness of the quantifiers, example
[^"]+
take all characters except "
, thus it stop when a "
is find.
Demo:
<?php
function a($menu_item, $remove_link) {
//$pattern = '~class="(.+)"(.+)<a.+>(.+)</a>~';
$pattern = '~class="([^"]+)"([^>]*>)<a[^>]+>([^<]+)<\/a>~';
if($remove_link) {
return preg_replace($pattern, 'class="$1 selected"$2$3', $menu_item);
}
return $menu_item;
}
$menu_item = '<li class="menuitem first"><a href="index.php">Home</a></li>';
echo a($menu_item, true);