简体   繁体   中英

how to match a particular string with preg_match?

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);

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;

 ?>

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
}

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);

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
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM