PHP Use preg_replace for replacing word with Doubl

2019-06-14 18:51发布

问题:

Possible Duplicate:
preg_replace how surround html attributes for a string with " in PHP

How to use preg_replace() for change all word that is within < > and after = for word with double quote surround

$var="<myfootball figure=thin new=aux(comment); > this=Association football < name=football >"

to

$var="<myfootball figure="thin"  new="aux(comment);" >this=Association footballl<  name="football"  >"

What is the regular expresion for do this with preg_replace()?

回答1:

Replace (?<==)(\b\w+\b)(?!")(?=[^<]*>) with "$1"

$var = preg_replace('/(?<==)(\b\w+\b)(?!")(?=[^<]*>)/', '"$1"', $var);

EDIT (based on OP's comment and question update) >>

Replace (?<==)(\b\S+?)(?=[\s>])(?!")(?=[^<]*>) with "$1"

$var = preg_replace('/(?<==)(\b\S+?)(?=[\s>])(?!")(?=[^<]*>)/', '"$1"', $var);


回答2:

I think it is better to put this in 2 regular expressions. The first expressions matches everything between < and > and the second expression quotes the text after =.

 $value = preg_replace_callback('|<(.*?)>|', function($matches) {
      // $matches[1] is now the text between < and >
      return '<'.preg_replace('|=(\w+)|', '="\\1"', $matches[1]).'>';
 }, $var);