Friday, 18 March 2016

Look Aheads, Look Behinds regular expression


http://infoheap.com/php-look-ahead-look-behind-regex/

//Negative look ahead

//Return true if string1(hello) is not followed by string2( world)
ট্রু রিটার্ন করে যদি একটা স্ট্রিং এর পরে আরেকটা স্ট্রিং না থাকে।
যেমন hello এর পরে যদি  wold না থেকে অন্য কিছু থাকলে তবে এটি match করবে। 
(এক্ষেত্রে ওয়ার্ল্ড এর আগে একটি স্পেস আছে) 
if (preg_match('/hello(?! world)/i', "hello something else", $matches, PREG_OFFSET_CAPTURE)) {

  echo "matched string:\n{$matches[0][0]} (at offset {$matches[0][1]})\n";

} else {

  echo "No match\n";

}



//Positive look ahead

//Return true if string1(hello) is followed by string2( world)

if (preg_match('/hello(?= world)/i', "hello world", $matches, PREG_OFFSET_CAPTURE)) {

  echo "matched string:\n{$matches[0][0]} (at offset {$matches[0][1]})\n";

} else {

  echo "No match\n";

}





//Negative look behind

//Return true if string2(world) is not preceded by string1(hello )
if (preg_match('/(?<!hello )world/i', "something world", $matches, PREG_OFFSET_CAPTURE)) {

  echo "matched string:\n{$matches[0][0]} (at offset {$matches[0][1]})\n";

} else {

  echo "No match\n";

}



//Positive look behind

//Return true if string2(world) is preceded by string1(hello )

if (preg_match('/(?<=hello )world/i', "hello world", $matches, PREG_OFFSET_CAPTURE)) {

  echo "matched string:\n{$matches[0][0]} (at offset {$matches[0][1]})\n";

} else {

  echo "No match\n";

}

No comments:

Post a Comment