0

Need to get and check for strings /get/ or /post/ only.

Following regex produce two results , but i actually need only the first one, how to correct this below regex query.

regex:  \/(post|get)\/

eg: http://www.google.com/get/

result:

Array
(
    [0] => /get/
    [1] => get
)

how to check for string /abcdef=/ -> regex used \/*=\/ , but it is not giving any results..

2 Answers2

0

You get two results because you use brackets for (get|post) If there are no brackets in a RegExp, the result would contain only the match itself. If there are brackets, then the 1st result will contain the global match, and each consequent result will contain the brackets content, in your case it's "get".

You just don't pay attention to $matches[1] and use $matches[0], consider the following:

$url = "domain.com/get/";
preg_match("/\/(post|get)\//", $url, $match);
$path = $match[0];
Oleg Dubas
  • 2,285
  • 1
  • 8
  • 24
0

From http://www.google.com/get/ if you want only get ,

You can use positive look ahead :

(?<=\/)(post|get)(?=\/)

Demo and Explanation

If you want to check /abcdef=/ you can use : (\/.*=\/)

Check Demo

Sujith PS
  • 4,447
  • 3
  • 29
  • 59