...

View Full Version : RegEx that works in PHP but not Javascript



ralph l mayo
12-17-2005, 06:56 AM
I have this:


$teststring = '<span style="font-weight: bold;">test</span></span>';
echo preg_replace('/<span style="font-weight: bold;">(.*)(?<!<\/span>)<\/span>/', '<strong>$1</strong>', $teststring);
// result: <strong>test</strong></span>


but in Javascript I get an error form this:


var text = '<span style="font-weight: bold;">test</span></span>';
text = text.replace(/<span style="font-weight: bold;">(.*)(?<!<\/span>)<\/span>/g, '<strong>$1</strong>');
/* result: invalid quantifier ? */


What am I missing? Or, what's another way to do this? I just want to make sure the expression matches the first closing span like in the PHP example, by default it matches the last.

_Aerospace_Eng_
12-17-2005, 07:12 AM
Maybe this will help.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title></title>
<script type="text/javascript">
function checkme(form){
if(!(/^<span style="font-weight: bold;">$/.test(form.thespan.value))){
form.thespan.focus();
alert('does not match');
return false;
}
else {
alert('it does match');
return false;
}
}
</script>
</head>

<body>
<form onsubmit="return checkme(this)">
<input type="text" name="thespan">
<input type="submit" value="submit">
</form>
</body>
</html>

ralph l mayo
12-17-2005, 07:36 AM
I think that just matches <span style="font-weight: bold;"> at the end of a string, while I need to match <span style="font-weight:bold;">(.*)(the first </span> after the opening tag) anywhere in the string.

liorean
12-17-2005, 08:39 AM
Well, this will only works in newer browsers, but try using a non-greedy match.)
re=/<span\sstyle="font-weight:\sbold;">.*?<\/span>/

JavaScript regex can't exclude strings from a pattern, I'm afraid, so this is probably the only way to do it unless you want to just search for the next '<'.

ralph l mayo
12-17-2005, 09:32 AM
Well, this will only works in newer browsers, but try using a non-greedy match.)
re=/<span\sstyle="font-weight: bold;">.*?<\/span>/

JavaScript regex can't exclude strings from a pattern, I'm afraid, so this is probably the only way to do it unless you want to just search for the next '<'.

Thanks!

felgall
12-17-2005, 10:19 PM
The piece it doesn't like is:

(?<!<\/span>)

The first < is messing it up as Javascript doesn't use that notation. If you want to use a lookahead group with NOT </span> you need to specify the following Javascript

(?!<\/span>)

of course making the prior group reluctant rather than greedy is a more familiar way to do it.

(.*?)



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum