0

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>
Community
  • 1
  • 1
  • You'll probably need a [parser instead of regular expressions](http://stackoverflow.com/a/1732454/143295)... – Nicole Sep 12 '13 at 04:47
  • 2
    While you are clear with what you want here (which is a great thing) you haven't mentioned any research so far, or posted any ideas on how you plan to do it. Generally folks here don't just write stuff for others, it's more about helping with problems :) – Fluffeh Sep 12 '13 at 04:50

1 Answers1

3

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.

Paul
  • 139,544
  • 27
  • 275
  • 264
  • 1
    And thanks for making my comment from 30 seconds ago (folks here don't just write your solution for you) totally and utterly invalid :) +1 anyhow lol. – Fluffeh Sep 12 '13 at 04:51