如何使用preg_replace从字符串中删除单个字符单词


How to remove single character words from string with preg_replace

给定以下输入 -

"I went to 1 ' and didn't see p"

,PHP 的 preg_replace 函数的正则表达式是什么,用于删除所有单个字符(和剩余的空格),以便输出为 -

"went to and didn't see".

我一直在寻找解决方案,但找不到。类似的例子不包括正则表达式的解释,所以我无法使它们适应我的问题。因此,如果您知道如何执行此操作,请提供正则表达式,但也将其分解,以便我了解它的工作原理。

干杯

试试这个:

$output = trim(preg_replace("/(^|'s+)('S('s+|$))+/", " ", $input));
  • (^|'s+)表示"字符串或空格的开头"
  • ('s+|$)的意思是"空格字符串的结尾"
  • 'S是单个非空格字符

implodeexplodearray_filter 的帮助下尝试

$str ="I went to 1 ' and didn't see p";
$arr = explode(' ',$str);
function singleWord($var)
{
  if(1 !== strlen($var))
  return $var;
}
$final = array_filter($arr,'singleWord');
echo implode(' ',$final);
//return "went to and didn't see"(length=19)

你需要两遍

首先是去掉所有单个字符

(?<=^| ).(?=$| ) replace with empty string

第二种是只留下单个空格

[ ]{2,} replace with single space

你最终会得到一个开头或结尾可能有空格的字符串。我只会用你的语言来修剪它,而不是用正则表达式来修剪它

例如,第一个正则表达式是用 php 编写的,例如

$result = preg_replace('/(?<=^| ).(?=$| )/sm', '', $subject);

试试这个正则表达式

''s+'S's+' -> ' '