嘿,如果其中存在单词,我想删除整行?通过PHP?
示例:hello world, this world rocks
。它应该做的是:如果它找到这个词hello
,它应该删除整行。我该怎么做,括号和引号之间也可能有单词。
谢谢。
$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);
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."
键盘。
你说这个词也可以是括号和引号之间的词。
如果只想要单词本身,或者在括号和引号之间,您可以strstr()
用这个替换...
preg_match('/\b["(]?hello["(]?\b/', $str);
爱迪生。
我假设括号中的意思是括号,引号的意思是双引号。
您也可以在多行模式下使用正则表达式,但是乍一看这段代码的作用并不明显......
$str = trim(preg_replace('/^.*\b["(]?hello["(]?\b.*\n?/m', '', $str));
相关问题。
如果你有一个这样的行数组
$lines = array(
'hello world, this world rocks',
'or possibly not',
'depending on your viewpoint'
);
您可以遍历数组并查找单词
$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
很好很简单:
$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.
}