1

I hope you can help me, I have an array with some filter words:

$dang=array('foo','bar','baz','qux');

User can write a text, I am getting it in a variable:

$answ=$_GET[answ];

If user write a text like: "I like this cabaret, it's so foo.", I want to print this:

Found: bar

"bar" is found in "cabaret", (First ocurrence only).

I found this function here Find first occurance of array value in a string

$firstMatch = array_shift(array_intersect(str_word_count(strtolower($answ), 1), $dang));

it's works, sadly it finds words only (text separated by spaces).

Any way to do it for full text?

2
  • Have you looked in the manual strpos() comes to mind Commented Jul 27, 2016 at 14:52
  • I tried iterating the array and search using stripos(), it's a good way to do it, do you know something 'shorter'? maybe a regular exp? Commented Jul 27, 2016 at 14:55

1 Answer 1

2

You can loop the array using foreach() and use strpos() to check if the value exists in the string:

$string = "Hello world";

foreach ( $dang as $dong ) {
    if ( strpos($string, $dong) !== false ) {
        echo "Found: ".$dong; 
    }
}

strpos() returns false if the needle was not found, otherwise the position of the start of the needle in the haystack (0 being the first character)

Sign up to request clarification or add additional context in comments.

1 Comment

This answer is right. You should add a foreach to iterate your array with your filters and it'll do what you need.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.