Hi
I'm not trained as a programmer but I get by in PHP, well I thought I did until I found this function! Basically, I have a problem where javascript is removing " " from my class atribute in html so
$str = "e; Here is some sample html that is <span class=aClass> getting broken </span>"e;;
echo preg_replace( '/class=ї^"e;]+>/', 'class="e;\\0"e; >', $str);
/*
////currently outputs
Here is some sample html that is <span class="e;class=aClass> getting broken </span>"e; >
////SHOULD output
Here is some smaple html that is <span class="e;aClass"e;> getting broken </span>
*/
Use 1 as a callback instead of 0 and add parentheses. 0 returns the whole matched string, 1 onwards returns parenthesis matches. Here's what I think would work:
$str = " Here is some sample html that is <span class=aClass> getting broken </span>";
echo preg_replace( '/class=([-_a-z0-9]*?)/i', 'class="\\1"', $str);
Not tested (at college, sucks) and I'm not a master of regexp, but hey.
However, if I'm thinking right, the HTML should still work without quotes as long as there's no space in the name...
thanks Bennettman, that works perfectly! I don't understand the callback thing yet, looks like I'll have to read about that one. You're right in saying that the class would still work but it wouldn't validate as xhtml without the quotes.
thanks,
ed.
Callback is really simple - it just returns matches and parts of them:
If you have say /class="(*?)"/i (which matches anything starting with class" and ending with ", case-insensitive), \\0 (or $0) will return everything (as an example, it might return class="moo"), and \\1 or $1 will return the contents of the first set of parentheses (in the example, it'll return moo). If you have a second set of parentheses in the search, \\2 or $2 will use that.
But, I wouldn't really worry about getting stuck there. Regexp is a real pain at times.