mon authentification i'm trying to replace this style="color:black;" with style=" /> mon authentification i'm trying to replace this style="color:black;" with style=" /> mon authentification i'm trying to replace this style="color:black;" with style="/>

Replace only quotes of a specific tag in a string php

233 views Asked by At

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

1

There are 1 answers

0
Wiktor Stribiżew On

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.