Page 1 of 1

RegExp again - Negative lookaheads

Posted: Sun Apr 03, 2005 3:21 pm
by Chris Corbyn
(1) This doesn't match:
>>>> I'm a String

(2) This doesn't match:
Something here >>>> I'm a string

(3) This does match:
Hello I'm a string >>>>

(4) This does match:
Hi again I'm a Stringy thing
How do I find "I'm a String" only if it DOESN't come after ">>>>" (">>>>" may be anywhere in the string) ?

I thought something like but it will match example (2) above and adding " .* " at the beginning then matches example (1) :?

Code: Select all

/^(?!>>>>).*I'm a String.*$/

Posted: Sun Apr 03, 2005 3:23 pm
by feyd

Code: Select all

<?php

$test = array
(
	'>>>> I\'m a String',					//	no match
	'Something here >>>> I\'m a string',	//	no match
	'Hello I\'m a string >>>>',				//	match
	'Hi again I\'m a Stringy thing'			//	match
);

foreach($test as $str)
{
	$ret = preg_match('#>>>>.*I\'m a string#is', $str, $match);
	echo var_export($ret,true) . &quote;\n&quote;;
	echo var_export($str,true) . ' does' . (!$ret ? '' : ' not') . ' match.' . &quote;\n&quote;;
	var_export($match);
	echo &quote;\n\n&quote;;
}

?>

Code: Select all

1
'>>>> I\'m a String' does not match.
array (
  0 => '>>>> I\'m a String',
)

1
'Something here >>>> I\'m a string' does not match.
array (
  0 => '>>>> I\'m a string',
)

0
'Hello I\'m a string >>>>' does match.
array (
)

0
'Hi again I\'m a Stringy thing' does match.
array (
)

Posted: Sun Apr 03, 2005 4:05 pm
by Chris Corbyn
*Drum roll* *feyd to the rescue!* :P