2

I have a string variable in PHP , its content is:

$var='<SPAN id=1 value=1 name=1> one</SPAN>
<div id=2 value=2 name=2> two</div >';
 ....

I need a function for surround html attributes with "" i need do this for the all meta-tag

,etc the result should be this:

$var='<SPAN id= "1" value="1" name="1"> one </SPAN>
<div id="2" value="2" name="2" > two</div >';
 ...

I need replace all =[a-z][A-Z][1-9] for ="[a-z][A-Z][1-9]". I need a regular expresion for preg_replace

4 Answers 4

1

You need to wrap it all in single quotes like this:

$myHtml='<SPAN id="1" value="1" name="1"> one </SPAN>
    <div id="2" value="2" name="2" > two</div >';
Sign up to request clarification or add additional context in comments.

3 Comments

thanks but I havent initially double quotes and it not appear for wrap it all in single quotes.
Okay, so your question is "How do I automatically add double quotes for these attributes?"
Note to down voter - check the pre-edit question to see why I have given this answer!
1

Its is the solution

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

thanks for Ωmega, its works on IE8

Comments

0

use a heredoc which removes the need to escape most anything except $:

$var = <<<EOL
<span id="1" value="1" name="1">one</span>
etc...
EOL

1 Comment

thanks but I havent initially double quotes to escape them. Replacement is the problem. I have this =text and I need ="text"
0

I would run the string through DOMDocument:

$var='<SPAN id=1 value=1 name=1> one</SPAN>
<div id=2 value=2 name=2> two</div >';

// Create a new DOMDocument and load your markup.
$dom = new DOMDocument();
$dom->loadHTML($var);

// DOMDocument adds doctype and <html> and <body> tags if they aren't
// present, so find the contents of the <body> tag (which should be
// your original markup) and dump them back to a string.
$var = $dom->saveHTML($dom->getElementsByTagName('body')->item(0));

// Strip the actual <body> tags DOMDocument appended.
$var = preg_replace('#^<body>\s*(.+?)\s*</body>$#ms', '$1', $var);

// Here $var will be your desired output:
var_dump($var);

Output:

string(85) "<span id="1" value="1" name="1"> one</span>\n<div id="2" value="2" name="2"> two</div>"

Please note that if $var has the potential to contain an actual <body> tag, that modifications will need to be made to this code. I leave that as an exercise to the OP.

2 Comments

its a good solution but i need this for IE8 and IE8's DOM dont surround atributes of metatag with "". IE8 do this <SPAN id=1 value=1 name=1> one</SPAN>. It is the problem because I need this solution.
This solution surrounds attributes with " characters, as I showed with the output.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.