正则表达式从字符串中删除单个字符


Regex to remove single characters from string

考虑以下字符串

breaking out a of a simple prison
this is b moving up
following me is x times better

所有字符串都已小写。我想删除任何"松散"的 a-z 字符,导致:

breaking out of simple prison
this is moving up
following me is times better

这可以通过 php 中的单个正则表达式来实现吗?

$str = "breaking out a of a simple prison
this is b moving up
following me is x times better";
$res = preg_replace("@''b[a-z]''b ?@i", "", $str);
echo $res;

怎么样:

preg_replace('/(^|'s)[a-z]('s|$)/', '$1', $string);

请注意,这还会捕获字符串开头或结尾的单个字符,但不会捕获与标点符号相邻的单个字符(它们必须用空格包围)。

如果您还想删除标点符号之前的字符(例如"the x."),那么这在大多数(英语)情况下应该可以正常工作:

preg_replace('/(^|'s)[a-z]'b/', '$1', $string);

作为单行:

$result = preg_replace('/'s'p{Ll}'b|'b'p{Ll}'s/u', '', $subject);

这匹配了在空格('s之前或后面的单个小写字母('p{Ll}),删除了两者。单词边界('b)确保只有单个字母确实匹配。/u修饰符使正则表达式 Unicode 感知。

结果:两边被空格包围的单个字母减少为单个空格。前面有空格但不后跟空格的单个字母将被完全删除,单个字母后面只有空格,但前面没有空格。

所以

This a is my test sentence a. o How funny (what a coincidence a) this is!

更改为

This is my test sentence. How funny (what coincidence) this is!

你可以尝试这样的事情:

preg_replace('/'b'S's'b/', "", $subject);

这就是它的意思:

'b    # Assert position at a word boundary
'S    # Match a single character that is a “non-whitespace character”
's    # Match a single character that is a “whitespace character” (spaces, tabs, and line breaks)
'b    # Assert position at a word boundary

更新

正如 Radu 所提出的那样,因为我使用了'S这将匹配的不仅仅是a-zA-Z.它也将匹配0-9_.通常,它会匹配更多,但由于它前面有 'b ,它只能匹配单词字符。

正如 Tim Pietzcker 在评论中提到的,请注意,如果您的主题字符串需要删除后跟非单词字符(如 test a (hello))的单个字符,这将不起作用。如果像这样在单个字符后面有多余的空格,它也会倒下

test a  hello 

但是您可以通过将表达式更改为 'b'S's*'b 来解决此问题

试试这个:

$sString = preg_replace("@'b[a-z]{1}'b@m", ' ', $sString);