I really can't believe that there isn't any article explaining using regular expression to find a position of a given string. It is very command to use strpos or stripos to find the first occurrences of a given string in PHP. However, problem comes if strpos or stripos gives you the wrong result. Assuming you are looking for the symbol "RM" (Ringgit) on a given text. However, on the given text there exist a word called "RMX9182 is the code for this item selling at RM2000". It is obvious that you want your program to retrieve the symbol on "RM2000" instead of "RMX9182". Using the following strpos or stripos will definitely give you a wrong result.
$text = "RMX9182 is the code for this item selling at RM2000"; $position = stripos($text, "RM"); // return 0
Using the following regular expression, we can use regex to pinpoint the correct symbol pattern we want. In this case,
$text = "RMX9182 is the code for this item selling at RM2000"; $pattern = "/RM\\d/i"; preg_match($pattern, $text, $matches, PREG_OFFSET_CAPTURE); print_r($matches);
It will print out the following array
Array ( [0] => Array ( [0] => RM2 [1] => 45 ) )
Notice that the second index, 45, is the index of the found text. Assuming we have more than one matches in our text,
$text = "RMX9182 RM90 is the code for this item selling at RM2000"; $pattern = "/RM\\d/i"; preg_match($pattern, $text, $matches, PREG_OFFSET_CAPTURE); print_r($matches);
It will still retrieve the first found text as shown below
Array ( [0] => Array ( [0] => RM9 [1] => 8 ) )
However, if you would like to find all the position on a string, just use preg_match_all instead as shown below,
$text = "RMX9182 RM90 is the code for this item selling at RM2000"; $pattern = "/RM\\d/i"; preg_match_all($pattern, $text, $matches, PREG_OFFSET_CAPTURE); print_r($matches);
It will gives you a result similar to the one shown below,
Array ( [0] => Array ( [0] => Array ( [0] => RM9 [1] => 8 ) [1] => Array ( [0] => RM2 [1] => 50 ) ) )
This may seems very simple and direct but developer often find it easier to just stick to stripos or strpos until things get a bit off. If it's pure string. native methods might be just the right tool for you but if patterns is require, nothing beats regular expression