问题
Hey, I want to remove the whole line if a word exists in it? through PHP?
Example: hello world, this world rocks
.
What it should do is: if it finds the word hello
it should remove the whole line.
How can i do that and there could be words in between brackets and inverted commas also.
Thanks.
回答1:
If you have an array of lines like so
$lines = array(
'hello world, this world rocks',
'or possibly not',
'depending on your viewpoint'
);
You can loop through the array and look for the word
$keyword = 'hello';
foreach ($lines as &$line) {
if (stripos($line, $keyword) !== false) {
//string exists
$line = '';
}
}
int stripos ( string $haystack , string $needle [, int $offset = 0 ] )
: http://www.php.net/manual/en/function.stripos.php
回答2:
$str = 'Example: hello world, this world rocks.
What it should do is:
if it finds the word hello it should
remove the whole line. How can i do that and there
could be words in between brackets and inverted commas also.';
$lines = explode("\n", $str);
foreach($lines as $index => $line) {
if (strstr($line, 'hello')) {
unset($lines[$index]);
}
}
$str = implode("\n", $lines);
var_dump($str);
Output
string(137) "What it should do is:
remove the whole line. How can i do that and there
could be words in between brackets and inverted commas also."
CodePad.
You said the word could be could be words in between brackets and inverted commas also too.
In the case of wanting the word only on its own, or between bracket and quotes, you could replace the strstr()
with this...
preg_match('/\b["(]?hello["(]?\b/', $str);
Ideone.
I assumed by brackets you meant parenthesis and inverted commas you meant double quotes.
You could also use a regex in multiline mode, however it won't be as obvious at first glance what this code does...
$str = trim(preg_replace('/^.*\b["(]?hello["(]?\b.*\n?/m', '', $str));
Related Question.
回答3:
Nice and simple:
$string = "hello world, this world rocks"; //our string
if(strpos($string, "hello") !== FALSE) //if the word exists (we check for false in case word is at position 0)
{
$string = ''; //empty the string.
}
来源:https://stackoverflow.com/questions/5377798/how-to-remove-line-if-word-exists-php