banner I am Dev. A Freelance Web Developer from India. I have been working on for 2 years on PHP/MySQL, AJAX and related coding.

And personally I almost like everything that is OpenSource. I usally experiement with different opensource projects like RubyOnRails, OpenSocial, Facebook API and many more. More...
Sep
28th

PHP Function : Search All Substrings Within A Text

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:
  1. 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:
  1. $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:
  1. Array  (  [0] => Hello  [1] => I made it!  )

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!

Like this post? Want to receive more like these!

Then, enter your email address here:

Delivered by FeedBurner


Do you like this article? then

Post a Comment