Can someone help me figure out to do this with PHP?

Question by PittsburghPenguins1166: Can someone help me figure out to do this with PHP?
Say I have a variable: $phrase = “The 16th president was Abraham Lincoln”.
And I have two sentences:
$sentences[0] = “The 16th president of the US was Abraham Lincoln”;
$sentences[1] = “The 1st president was George Washington”.

Using PHP, what would be the best way to pick the $sentences that is contains the $phrase.
I can’t use strpos because in $sentences[0], the one that should be picked, contains a few words between the $phrase words. Is there anyway to use a wildcard or anything? Any ideas?

Best answer:

Answer by skaldromysarg
I think you are looking for “regular expressions”. To solve this problem, you need to define exactly what “that is contains” means:
– Do all the words of phrase have to appear in the sentence in the correct order, but any number of words can appear between them?
– Can it only differ in one spot?

For the former, this could be a solution:
$sentence) {
  if(preg_match($regexp, $sentence)) {
    echo “Sentence $index matches: \””.$sentence.”\”\n”;

Give your answer to this question below!

Add a Comment

Your email address will not be published. Required fields are marked *