• Status: Solved
  • Priority: Low
  • Security: Public
  • Views: 57
  • Last Modified:

Find all occurrences of a Substring in a String

Dear all,

Could someone help me fox fixing this function?

When I execute the script I receive an error message:

Warning:  count(): Parameter must be an array or an object that implements Countable in

<?php
function tag_contents($string, $start, $end){
   foreach (explode($start, $string) as $key => $value) {
       if(strpos($value, $end) !== TRUE){
            $result[] = substr($value, 0, strpos($value, $end));
//			 $result[] ="<strong>".$start."</strong>" . substr($value, 0, strpos($value, $end)) . "<strong>".$end."</strong>";
     	  	   
	   [b]if(count($result[$key]) > 150 || str_word_count($result[$key]) > 15)   [/b]
	   
	    {
	    
        unset($result[$key]);
					}
		   }
   
   }
   return $result;	 
}

?>

Open in new window



I want limit the output to substring with less than 15 words and 150 characters.

Thanks

Bob
0
BOB KUSPE
Asked:
BOB KUSPE
  • 3
1 Solution
 
gr8gonzoConsultantCommented:
I think this:
if(count($result[$key])
should be
if(strlen($result[$key])
1
 
gr8gonzoConsultantCommented:
Also this:
if(strpos($value, $end) !== TRUE){

...probably does not work exactly like you want it to work. strpos will NEVER return a boolean True value. It either returns a number indicating the position of the substring, which can be 0 or greater, OR if the substring is not found, it returns a FALSE boolean. So that code will literally run every single time because it will either be false or a number, and neither of which will ever be a boolean of true.

So if you did this:
if(strpos($value, $end) !== FALSE){
...then that would mean "Run the following code if $end is found ANYWHERE inside $value"

So if $end was NOT found inside $value, then it would skip over that section of code.
0
 
gr8gonzoConsultantCommented:
In fact, since you're checking it twice, just assign it to a variable and test it.

$endPos = strpos($value, $end);
if(endPos !== FALSE){
            $result[] = substr($value, 0, $endPos);

Open in new window

0
 
BOB KUSPEAuthor Commented:
Many Thanks
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now