【问题标题】:How to remove first word of sentence and replace by another?如何删除句子的第一个单词并替换为另一个?
【发布时间】:2020-01-16 22:36:52
【问题描述】:

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

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

$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';
}


请帮忙。我收到了许多类似的相关答案,但没有得到预期的答案。我希望使其与不区分大小写的情况一起使用。

【问题讨论】:

  • 问题可能是你正在寻找hello.,它的末尾有一个.,你正在搜索的文本在Hello,的末尾有一个,。跨度>
  • 谢谢@NigelRen .. 但问题是用另一个词替换你好。
  • (stripos($var, 'hello') !== 0)替换(stripos($var, 'hello.') !== false)

标签: php arrays regex string replace


【解决方案1】:

我不能 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;

【讨论】:

    【解决方案2】:

    您可以使用strpos

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

    【讨论】:

      猜你喜欢
      • 2019-09-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多