-1

In a string like this one

Améliorer <span style="color:black;">mon authentification</span>

i'm trying to replace this

style="color:black;"

with

style= \ "color:black; \ "

i'm trying to use preg_replace like that

$result = preg_replace('/(<*[^>]*style=)"[^>]+"([^>]*>)/', '\1\"300\"\2', $data);

but in this way i only change the content of style attribute while the content should remains the same.

i've to change it only on style attribute because i need to keep some double quotes inside the string (so i can't str_replace)

Thanks

dack funk
  • 43
  • 6

1 Answers1

1

You can use

$data = 'Améliorer <span style="color:black;">mon authentification</span>';
echo preg_replace('/(<[^>]*\sstyle=)"([^"]+)"([^>]*>)/', '\1\"\2\"\3', $data);

See the PHP demo and the regex demo.

Details:

  • (<[^>]*\sstyle=) - Group 1: <, then any zero or more chars other than > and then a whitespace and style= string
  • " - a double quote
  • ([^"]+) - Group 2: any one or more chars other than "
  • " - a " char
  • ([^>]*>) - Group 3: any zero or more chars other than > and then a > char.

Note that there are three capturing groups around the parts that we need to keep and the double quotation marks are left outside of capturing groups, so that they could be replaced/removed.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563