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

时间:2017-09-29 13:21:25

标签: php

例如,这句话:

" 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"

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

" Hello Humanity D."

" Today weather, good D."

" I could not find another sentence 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. "));

Image

5 个答案:

答案 0 :(得分:2)

快速的一行方式:

<?php

echo trim(str_replace(' D.', '', strstr($string, ' 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

答案 1 :(得分:0)

使用preg_replace

$re = '/.*D\.\s*(.*)/';
$str = 'Hello Humanity D. Humanity is a wonderful thing';
$subst = '$1';

$result = preg_replace($re, $subst, $str);

echo $result;

结果: Humanity is a wonderful thing

答案 2 :(得分:0)

您可以找到&#39; D。&#39;的位置。 strpos和substract后是什么。

$ new_sentance = substr($ sentance,strpos($ sentance,&#39; D。&#39;)+ 1);

答案 3 :(得分:0)

另一个建议:

$str = 'Hello Humanity D. Humanity is a wonderful thing';
$a = explode("D.",$str);
array_shift($a);
$result = trim(implode("", $a));

这样你就不必摆弄正则表达式了。 速度比较:http://sandbox.onlinephpfunctions.com/code/a078d7ca01c149aabaaddb335a4b0ad8669fb273

答案 4 :(得分:-1)

试试这个正则表达式:https://regex101.com/r/mvoJDs/1/

if (Cookies.get('pageA-selection')) {
  // Assuming you trigger the ajax request by a click handler on the list item
  $('#'+Cookies.get('pageA-selection')).click();
}

将输出:

<?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);

在此处查看https://3v4l.org/kfPnm