0

I can't find the documentation that indicates how to do it. I am dynamically displaying a part of a post description in the search results from my website.

Example:

<?php
$extract = "Include all the information someone would need to answer your question.";
$search = "format";
$num = stripos($extract,$search);

$to_show = substr($extract,$num, 17);

echo $to_show;
?>

Result:

formation someone

I would like to be able to show "information" and not "formation". Any suggestion?

gomez
  • 15
  • 4
  • What if your sentence is: "Include all the formatted information someone would need to answer your question." – talha2k Jan 25 '22 at 03:21
  • Sorry but I don't understand you because your example is the same as mine although I am getting post descriptions dynamically, it can be any text and occasionally it gives the result I show. – gomez Jan 25 '22 at 03:33
  • you are searching for "format" what if the string comes in twice in your string? Like my example. then what will you expect the output to be? – talha2k Jan 25 '22 at 03:36
  • I think I know what you mean, use $matches[0][0] based on the answer you mark as correct because I think I didn't formulate my question completely and clearly. @Tim Biegeleisen helped me correctly anyway! But the problem I have is different now because I have to replace the first word obtained by the first word part of the match from my example. I will find how to do it. Thanks a lot! – gomez Jan 25 '22 at 04:11

1 Answers1

0

Actually regular expressions work nicely for your particular problem. Search for \w*format\w* using preg_match_all:

$extract = "Include all the information someone would need to answer your question.";
preg_match_all("/\w*format\w*/", $extract, $matches);
print_r($matches[0]);

This prints:

Array
(
    [0] => information
)
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
  • Thank! Great, this works great. I would only have to replace the word obtained by the one at the beginning of the string so as not to duplicate it, do you know how to do it? Using $matches[0][0] it looks like this: informationformation someone – gomez Jan 25 '22 at 04:06
  • @gomez The answer I gave does a _search_, but your comment seems to want a replacement. If you want to replace, you could use `preg_replace("/\w*format\w*/, "something", $extract)` – Tim Biegeleisen Jan 25 '22 at 04:09