Sep
28th
Author: Dev |
Files under PHP
Hope, you know about the built-in PHP function substr which finds a substring with a given string between the given postions. But, there is no built-in PHP function which returns substrings positioned between a given starting and ending charecters. So, here is the function which exactly does this work.
PHP:
-
function isubstr($text, $sopener, $scloser) { $result = array(); $noresult = substr_count($text, $sopener); $ncresult = substr_count($text, $scloser); if ($noresult < $ncresult) { $nresult = $noresult; } else { $nresult = $ncresult; } unset($noresult); unset($ncresult); for ($i = 0; $i < $nresult; $i++) { $pos = strpos($text, $sopener) + strlen($sopener); $text = substr($text, $pos, strlen($text)); $pos = strpos($text, $scloser); $result[] = substr($text, 0, $pos); $text = substr($text, $pos + strlen($scloser), strlen($text)); } return $result; }
For example:
PHP:
-
$text = "Hello, This is a great day. I made it!"; $result_array = isubstr($text, "", ""); print_r($result_array);
This will result result in the following output:
PHP:
As this will find all the matchs in the text, you can use this in case of single and multiple searches in the text. Hope this helps! Enjoy!
I am Dev. A Freelance Web Developer from India. I have been working on for 2 years on PHP/MySQL, AJAX and related coding.