0

In the following string, I would like to delete "class2" and "class3" in the class attribute of the span tag

Right now, I'm doing this:

$string = '<span class="class1 class2 class3">class1 class2 class3</span>';

$patterns = array();
$patterns[0] = '/class2/';
$patterns[1] = '/class3/';

$replacements = array();
$replacements[0] = '';
$replacements[1] = '';

$string = preg_replace($patterns, $replacements, $string);

echo htmlspecialchars($string);

This returns:<span class="class1 ">class1 </span>

This not exactly what I want.

I would like it to return: <span class="class1">class1 class2 class3</span>

I don't know what kind of pattern I have to to use to make the replacements only inside the class attribute

Thanks for your help!

Vincent
  • 1,651
  • 9
  • 28
  • 54
  • See also [why it's a bad idea to try and do this using regexes](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags). – Charles Feb 15 '12 at 19:30

1 Answers1

0

You can use

preg_replace('/class="class1[^"]*/', 'class="class1', $string);
JRL
  • 76,767
  • 18
  • 98
  • 146
  • I see the logic behind your pattern but unfortunately, the class attribute can have a lot of values. I know in advance the set of data I want to delete inside it, but I don't know in advance what other values there will be inside. I would like to target and erase only specific values. – Vincent Feb 15 '12 at 01:44