1

ねえ、単語が含まれている場合は、行全体を削除したいですか?PHPを介して?

例:hello world, this world rocks。何をすべきか:単語が見つかった場合は、hello行全体を削除する必要があります。どうすればそれを行うことができ、角かっこと逆コンマの間に単語が含まれる可能性もあります。

ありがとう。

4

3 に答える 3

4
$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."

CodePad

単語は角かっこと逆コンマの間の単語である可能性もあるとあなたは言いました。

単語だけが必要な場合、または角かっこと引用符の間にある場合は、strstr()をこれに置き換えることができます...

preg_match('/\b["(]?hello["(]?\b/', $str);

イデオネ

角かっこは括弧を意味し、逆コンマは二重引用符を意味すると仮定しました。

マルチラインモードで正規表現を使用することもできますが、このコードが何をするのかは一見しただけではわかりません...

$str = trim(preg_replace('/^.*\b["(]?hello["(]?\b.*\n?/m', '', $str));

関連する質問

于 2011-03-21T12:56:55.543 に答える
1

あなたがそのような行の配列を持っているなら

$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

于 2011-03-21T12:56:13.683 に答える
0

素晴らしくてシンプル:

$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.
}
于 2011-03-21T12:55:01.377 に答える