Php 在句子中搜索单词并删除以前的单词

Php 在句子中搜索单词并删除以前的单词,php,Php,例如,这句话: “你好,人类D.人类是一件奇妙的事情” “今天天气好,明天可能不好” “我找不到另一个句子D。最后一个示例句子” 我有495句这样的句子。 这是要删除的句子 “你好,人类D.” “今天天气好,D.” “我找不到另一个句子D.” 每个字母的共同特征是字母“D.”的存在 如何删除D.之前的句子 function removeEverythingBefore($in, $before) { $pos = strpos($in, $before); return $pos

例如,这句话:

你好,人类D.人类是一件奇妙的事情

今天天气好,明天可能不好

我找不到另一个句子D。最后一个示例句子

我有495句这样的句子。 这是要删除的句子

你好,人类D.

今天天气好,D.

我找不到另一个句子D.

每个字母的共同特征是字母“
D.
”的存在

如何删除
D.
之前的句子

function removeEverythingBefore($in, $before) {
    $pos = strpos($in, $before);
    return $pos !== FALSE
        ? substr($in, $pos + strlen($before), strlen($in))
        : "";
}
echo(removeEverythingBefore("I could not find another sentence D. this last example sentence", "D. "));

带有:

结果:
人性是一件奇妙的事情

一种快速的单行方式:

<?php

echo trim(str_replace(' D.', '', strstr($string, ' D.')));

你可以用strop和后面的减法找到“D”的位置

$new_sentance=substr($sentance,strpos($sentance,'D.))+1)

试试这个正则表达式:

查看此处的工作情况

另一个建议:

$str = 'Hello Humanity D. Humanity is a wonderful thing';
$a = explode("D.",$str);
array_shift($a);
$result = trim(implode("", $a));
这样你就不必再摆弄正则表达式了。
速度比较:

显示您的预期输出和您迄今为止尝试过的代码您正在寻找正则表达式。尝试过的
preg_replace()
?这里不需要正则表达式,为什么不
explode()
?因为它可能包含多个
D.
这有什么问题吗?分解>阵列移位>内爆修剪(分解->阵列移位->内爆),这只是太多的步骤了!具有讽刺意味的是,你的代码甚至不适用于2“D”。他希望在D之前删除整个句子。这就是上面所做的。如果句子是“我为CND竞选”怎么办?当它不应该被移除时,它会被移除。也许在D之前调整一下空间?谢谢:D
<?php

$string = 'I could not find another sentence D. this last example sentence';

echo trim(str_replace(' D.', '', strstr($string, ' D.')));
//Outputs: this last example sentence
<?php

$strings = [
'Hello Humanity D. Humanity is a wonderful thing',
'Today weather, good D. maybe tomorrow will be bad',    
'I could not find another sentence D. this last example sentence',    
'I have 495 sentences for like this. Here are the sentence to be deleted',   
'Hello Humanity D. ',   
'Today weather, good D. ',    
'I could not find another sentence D.     '
];

$regex =  '#.+\sD\.\s#';

foreach ($strings as $key => $val) {
    $strings[$key] = preg_replace($regex, '', $val);
}

var_dump($strings);
array(7) { 
[0]=> string(29) "Humanity is a wonderful thing" 
[1]=> string(26) "maybe tomorrow will be bad" 
[2]=> string(26) "this last example sentence" 
[3]=> string(71) "I have 495 sentences for like this. Here are the sentence to be deleted" 
[4]=> string(0) "" 
[5]=> string(0) "" 
[6]=> string(4) " " 
}
$str = 'Hello Humanity D. Humanity is a wonderful thing';
$a = explode("D.",$str);
array_shift($a);
$result = trim(implode("", $a));