Loek van Kooten
Loek van Kooten

Reputation: 123

RegEx for replacing all occurrences of character between two delimiters

I need the help of some RegEx gods here, as I've tried for two hours and can't wrap my head around this:

Sample source:

DisplayText="cf font="Arial" size="10" complexscriptsfont="Arial" complexscriptssize="10" asiantextfont="Arial" fontcolor="595959"">

I want to replace all instances of " with " but only if these are inside the enclosing ". I.e. the above should become:

DisplayText="cf font="Arial" size="10" complexscriptsfont="Arial" complexscriptssize="10" asiantextfont="Arial" fontcolor="595959"">

The exact structure of the text inside DisplayText is unknown and varies all the time, but whatever the case, we don't want " within the outer ". As you can see, the outer " are left untouched. This should only occur in strings starting with DisplayText=" and ending with ">.

So finding the strings that need editing is easy:

/DisplayText\="(.*?)"\>/

Now we just need to replace " with " within $1 only.

This is for PHP.

Help would be much appreciated!

Upvotes: 0

Views: 241

Answers (2)

Loek van Kooten
Loek van Kooten

Reputation: 123

In the end this worked!

$postproc = preg_replace('#(DisplayText="|\G(?!\A))([^">]*)"(?!\s*>)#', '$1$2"', $postproc);

So I just had to add DisplayText to prevent the RegEx from becoming overzealous and start touching other tags in the XML.

Thank you all and especially revo for that suggestions I just seem not to be able to upvote revo's comment?

Upvotes: 2

bestestefan
bestestefan

Reputation: 871

How about this code:

https://3v4l.org/6qHhb

$str = 'DisplayText="cf font="Arial" size="10" complexscriptsfont="Arial" complexscriptssize="10" asiantextfont="Arial" fontcolor="595959"">';
$splitted = explode('"', $str);
$splittedSize = count($splitted);
$result = $splitted[0].'"'.implode('"',array_slice($splitted,1,$splittedSize-2)).$splitted[$splittedSize-1].'"';
echo $result;

Upvotes: 0

Related Questions