Reputation: 203
I want to match following pattern India
in the string "$str=Sri Lanka Under-19s 235/5 * v India Under-19s 503/7 "
. It should return false because instead of India
, India Under-19s
is present? If only India
is present without under 19 how to do this with regex. Please help.
It should match only if india
is present and should fail if india under-19
is present.
I have written following code for this but it is always matching-
$str="Sri Lanka Under-19s 235/5 * v India Under-19s 503/7";
$team="#India\s(?!("Under-19s"))#";
preg_match($team,$str,$matches);
Upvotes: 1
Views: 372
Reputation: 432
Assuming a single white space between India and Under-19s regular expression to check for that would be.
/India\s(?!Under)/
Put all together in code
$string = "Sri Lanka Under-19s 235/5 * v India Under-19s 503/7";
$pattern="/India\s(?!Under)/";
preg_match($pattern,$string,$match);
if(count($match)==0){
//What we need
}else{
//Under-19 is present
}
Upvotes: 1
Reputation: 4373
This does what you are asking:
<?php
$str="Sri Lanka Under-19s 235/5 * v India Under-19s 503/7";
$team="/India\s(?!Under-19s)/";
preg_match($team,$str,$matches);
exit;
?>
Upvotes: 2
Reputation: 2083
Matching the lack of a string in a regexp is a bit ugly. This is a little clearer:
$india_regexp = '/india/i';
$under19_regexp = '/under-19s/i';
$match = preg_match(india_regexp, $str) && ! preg_match(under19_regexp, $str);
Upvotes: 1
Reputation: 1529
My solution:
$text = "Sri Lanka Under-19s 235/5 * v India Under-19s 503/7";
$check = explode(" ", strstr($text, "India"));
if( $check[1] == "Under-19s" ){
// If is in text
}else{
// If not
}
Upvotes: 1