RegExp again - Negative lookaheads

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

RegExp again - Negative lookaheads

Post 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.*$/
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post 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 (
)
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post by Chris Corbyn »

*Drum roll* *feyd to the rescue!* :P
Post Reply