1
    this is a sentence oil on a line
    this is another sentence
    another one
    hey oil sentence

I have these 4 sentences, what I want to do is to check if this sentence(each sentence is on a line) has the word oil. And if it does I would delete the whole sentence.

So I'll End up with this:

    this is another sentence
    another one

the lines including oil has been removed.

I had an idea of exploding these lines to an array. Then use foreach to check for oil. Deleting the element, then imploding.

But I was wondering if there are any faster ways?

the sof asker
  • 59
  • 1
  • 6

3 Answers3

0

You could use the strpos function. Here is a related question: How do I check if a string contains a specific word in PHP?.

Community
  • 1
  • 1
Brock B.
  • 367
  • 1
  • 13
0

While your idea with explode would work, there are easier ways. You can use strpos to find a substring within a string. If no substring is found it will return false. If you want case insensitivity you can for the original string to be all lowercase (or uppercase) with strtolower (or strtoupper ):

if( strpos(strtolower($string),'oil')!==false )
{
    // string found
}
else
{
    // string not found
}
Muhammad Abdul-Rahim
  • 1,980
  • 19
  • 31
0

use strpos() function in php, if that particular string has a position then that means that your string has that particular word or character.

Just have a look at a simple solution as per your requirement

 foreach( explode($wholesentence,"\n" ) as $yourstrimg )
    if (strpos($yourstrimg,'oil') !== false) {
        echo 'oil';
    }
}

Note:

"\n" is just used to indicate new line here, it can also be different line break operator change in different languages, like in html it is "<br />"

Sourabh Kumar Sharma
  • 2,864
  • 3
  • 25
  • 33