使用 PHP 从字符串中的所有单词中删除 s 或 's



我在PHP 中有一个字符串

$string = "Dogs are Jonny's favorite pet";

我想使用regex或某种方法从字符串中所有单词的末尾删除s's

所需输出为:

$revisedString = "Dog are Jonny favorite pet";

这是我目前的方法:

<?php
$string = "Dogs are Jonny's favorite pet";
$stringWords = explode(" ", $string);
$counter = 0;
foreach($stringWords as $string) {
if(substr($string, -1) == s){
$stringWords[$counter] = trim($string, "s");
}

if(strpos($string, "'s") !== false){
$stringWords[$counter] = trim($string, "'s");
}

$counter = $counter + 1;
}
print_r($stringWords);
$newString = "";
foreach($stringWords as $string){
$newString = $newString . $string . " ";
}
echo $newString;
}

?>

REGEX将如何实现这一目标?

对于一般用途,您必须利用比不懂英语的regex模式更复杂的技术。可能存在以下图案因移除不应该移除的s而失败的条纹情况。它可以是一个名字,一个缩写,或其他什么。

作为一种不可靠的解决方案,如果撇号前面没有另一个s,则可以选择匹配撇号,然后匹配文字s。在词尾添加单词边界(b(可以提高匹配词尾的准确性。

代码:(演示(

$string = "The bass can access the river's delta from the ocean. The fishermen, assassins, and their friends are happy on the banks";
var_export(preg_replace("~'?(?<!s)sb~", '', $string));

输出:

'The bass can access the river delta from the ocean. The fishermen, assassin, and their friend are happy on the bank'

最新更新