user2771132
user2771132

Reputation: 1

Using preg_replace exclusion inside < and >

I want to replace all " not inside <...> to '

Example

My string:

Hello "world" <a href="#" title="some text">abc</a>

I want this after replacement:

Hello 'world' <a href="#" title="some text">abc</a>

Upvotes: 0

Views: 55

Answers (1)

Paul
Paul

Reputation: 141827

This will work in most cases:

$result = preg_replace('/^((?:[^<"]|(?:<[^>]*>))*)"([^"]*)"/', "$1'$2'", $str);

It will not work if you have a > character in an HTML attribute. To catch all those edge cases you should avoid regex, and look into more powerful tools designed for parsing HTML, since HTML is not a regular language.

Upvotes: 3

Related Questions