I've now rewritten this as a function that takes 4 parameters: two pairs of search/replace "preg" style parameters, and of course the string... and also a "flags" parameter so you can add "caseless" etc. So there are 6 total.
This works very well and it has a lot of options and seems organized, at least compared to the versions in my previous posts. However, it is still very specific and may have problems if someone's needs differ too greatly from mine-- basically if it's anything other than standard "tags" where there's an open and a close tag, and the close tag doesn't have any variable parts. It actually would work fine, I think, but it could get complex because of the for loop at the end. That is the only part that would (I think) cause problems.
PHP Code:
<?php
//replace recursively requiring matching pairs, such as html tags
function preg_replace_recursivepair($po,$pc,$ro,$rc,$s,$flags='') {
//pattern open, pattern close, replace open, replace close, string, preg flags
$level = 0;
$s = preg_replace_callback('/'.$po.'|'.$pc.'/'.$flags,
function ($matches) use (&$level,$po,$pc,$ro,$rc) {
if (preg_match('/'.$po.'/'.$flags,$matches[0])==1) {
$level++; //going up one level
return preg_replace('/'.$po.'/'.$flags,$ro,$matches[0]);
}
else {
if ($level>0) { //valid level?
$level--; //going down one level
return preg_replace('/'.$pc.'/'.$flags,$rc,$matches[0]);
}
else {
return $matches[0]; //no changes, invalid
}
}
},
$s);
for(;$level>0;$level--) {
$s .= $rc;
}
return $s;
}
$s = '[label=A long sentence.]Una [label=sentence]frase[/label] grande.[/label][/label] [label=Goodbye.]Adiós.';
echo preg_replace_recursivepair('\[label=(.+)\]','\[\/label\]','<span title="$1">','</span>',$s,'Uiu');
?>
Note: I changed my translated text from Italian to Spanish now that I set my file's format to UTF8 and that works....
I'd like some feedback on this and perhaps some ideas on standardizing it.
And I still know there must be a simpler/normal way to do this...
Bookmarks