简体   繁体   中英

php string replace only within html tags ie <here> of a string

I have PHP strings that have HTML inside of them, which I am storing inside JavaScript variables for later use. The problem is that the content of the JavaScript variable is encompassed by " s, so any " s inside of the PHP string will break the variable.

Right now I have

$content=str_replace ('"','&quot;', $phpstring);

Which will make all " s encoded so that any inside text that I want displayed will work fine, but the problem is that the " s within tags eg <p id="para1"> will be replaced with <p id=&quot;para1&quot;> . But what I want to do is replace the " s within tags ie between < and > , with a ' , so that they still work properly, and the " s not within tags to be replaced with &quot; , like I have it currently.

It works fine right now but that is only because I have changed all of the " s in tags by hand.

Have you tried addslashes? It might work. Documentation is found here: http://dk.php.net/addslashes

The answer to your question is the preg_replace function. However you shouldn't need to use it I dont think. You can manually add escape slashes with str_replace or use the addslashes function as mentioned in another answer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM