查找并替换所有以 'ing' 结尾的单词
Finding and replacing all words that ends with 'ing'
我正在尝试查找并替换所有以 'ing' 结尾的单词。我该怎么做?
$text = "dreaming";
if (strlen($text) >= 6) {
if (0 === strpos($text, "ing"))
//replace the last 3 characters of $text <---not sure how to do this either
echo $text;
echo "true";
}
结果:
null
想要的结果:
dream
true
$text = "dreaming";
if (strlen($text) >= 6 && strpos($text,'ing')) {
echo str_replace('ing', '', $text);
echo "true";
}
你应该看看手册。有许多不同的字符串函数和不同的方法可以完成此操作:
http://php.net/manual/en/ref.strings.php
既然你坚持了:
$text = "dreaming";
if (strlen($text) >= 6 && substr($text,strlen($text)-3)=='ing') {
echo str_replace('ing', '', $text);
echo "true";
}
这应该适用于替换单词末尾的 ing,同时忽略以 Ing 开头的内容以及中间带有 ing 的单词。
$output = preg_replace('/(\w)ing([\W]+|$)/i', '', $input);
已更新以反映评论中指定的更改。
您也可以使用 substr
$text = "dreaming";
if (substr($text, (strlen($text) - 3), 3) === 'ing') {
$text = substr($text, 0, (strlen($text) - 3));
}
echo $text;
您可以使用两个正则表达式,具体取决于您要解决的问题。您的问题有点模棱两可。
echo preg_replace('/([a-zA-Z]+)ing((:?[\s.,;!?]|$))/', '', $text);
或
echo preg_replace('/.{3}$/', '', $text);
第一个正则表达式查找 ing
之前的单词字符,然后是标点符号、空格或字符串结尾。第二个只是去掉字符串的最后三个字符。
您可以使用 regex and word boundaries.
$str = preg_replace('/\Bing\b/', "", $str);
\B
(非单词边界)匹配单词字符粘在一起的地方。
请注意,它将 king
替换为 k
。参见 demo at regex101
我正在尝试查找并替换所有以 'ing' 结尾的单词。我该怎么做?
$text = "dreaming";
if (strlen($text) >= 6) {
if (0 === strpos($text, "ing"))
//replace the last 3 characters of $text <---not sure how to do this either
echo $text;
echo "true";
}
结果:
null
想要的结果:
dream
true
$text = "dreaming";
if (strlen($text) >= 6 && strpos($text,'ing')) {
echo str_replace('ing', '', $text);
echo "true";
}
你应该看看手册。有许多不同的字符串函数和不同的方法可以完成此操作: http://php.net/manual/en/ref.strings.php
既然你坚持了:
$text = "dreaming";
if (strlen($text) >= 6 && substr($text,strlen($text)-3)=='ing') {
echo str_replace('ing', '', $text);
echo "true";
}
这应该适用于替换单词末尾的 ing,同时忽略以 Ing 开头的内容以及中间带有 ing 的单词。
$output = preg_replace('/(\w)ing([\W]+|$)/i', '', $input);
已更新以反映评论中指定的更改。
您也可以使用 substr
$text = "dreaming";
if (substr($text, (strlen($text) - 3), 3) === 'ing') {
$text = substr($text, 0, (strlen($text) - 3));
}
echo $text;
您可以使用两个正则表达式,具体取决于您要解决的问题。您的问题有点模棱两可。
echo preg_replace('/([a-zA-Z]+)ing((:?[\s.,;!?]|$))/', '', $text);
或
echo preg_replace('/.{3}$/', '', $text);
第一个正则表达式查找 ing
之前的单词字符,然后是标点符号、空格或字符串结尾。第二个只是去掉字符串的最后三个字符。
您可以使用 regex and word boundaries.
$str = preg_replace('/\Bing\b/', "", $str);
\B
(非单词边界)匹配单词字符粘在一起的地方。
请注意,它将 king
替换为 k
。参见 demo at regex101