如何删除句子的第一个单词并替换为另一个单词?

时间:2019-09-16 05:41:29

标签: php arrays regex string replace

我有多个段落是动态循环的。在检查段落的第一个单词是否包含我要寻找的关键字之后,我只想在这些段落上添加前缀。

我尝试了很多次,但仍无法获得完美的答案。

$var="Hello, this paragraph is a series of related sentences developing a central idea, called the topic. Try to think idea.";
if (stripos($var, 'hello,') !== false) {
echo 'true';
}


请对此提供帮助。我收到了许多类似的相关答案,但没有得到预期的答案。我希望使其不区分大小写。

2 个答案:

答案 0 :(得分:0)

我不确定100%是否正确理解您的问题,但是也许您可以尝试一下。

$var = "Hello, this paragraph is a series of related sentences developing a central idea, called the topic. Try to think idea.";

if (stripos($var, 'hello,') === 0) {
    // this checks if the searched word is exactly at the beginning of the string
    $var = 'YOUR PREFIX -- ' . $var;
}

echo $var;

如果要替换第一个单词,则应使用该代码。

$var = "Hello, this paragraph is a series of related sentences developing a central idea, called the topic. Try to think idea.";

if (stripos($var, 'hello,') === 0) {
    // this checks if the searched word is exactly at the beginning of the string
    $var = preg_replace('/hello\,/i', 'REPLACE WITH', $var, 1);
}

echo $var;

答案 1 :(得分:0)

您可以使用strpos

if(strpos($var, 'Hello,') === 0 || strpos($var, 'hello,') === 0){
  //Your Logic
}