Search code examples
phpspacesubstrstrpos

Find substring in string when beginning with some string to space (whole word)


I'm trying to find substring from string and get that part from it that begins width word - $search. Now, it's working but I want to find this substring to whole word, to space. How to do that?

I'm using:

  $results[] = [ 'value' => substr(strip_tags($query->content), strpos(strip_tags($query->content),$search) ,30)];

I also tried with:

 $results[] = [  'value' => substr(strip_tags($query->content), strpos(strip_tags($query->content),$search) ,strpos(strip_tags($query->content), ' ',30))];

But it finds substring not to interval.

Edited: I did it, but all records repeat two times. I have to show title and content only twice. I had to make loop for $matches but now, recoreds repeat. How to fix that? Thanks.

foreach ($sql as $query) {


preg_match('#(' . preg_quote($search, '#') . '.{30,}?)\s#', strip_tags($query->content), $matches);

foreach($matches as $key=>$val) {
$results[] = [  'id' => $query->title, 'value' => $val];
}

}

return $results;


Solution

  • This can easily be done with regex

    preg_match('#(' . preg_quote($search, '#') . '.{30,}?)\s#', strip_tags($query->content), $match);
    $results[] = [ 'value' => $match[1] ];