首页 > 解决方案 > 从字符串中删除所有数字,除非它们遵循 PHP 中的某个字符

问题描述

假设我有许多字符串,其中字符没有预定义的位置......

$string = '324 Example words #25 more words';
$string2 = 'Sample words 324 Example words #25 more words #26';

我想删除 php 字符串中的所有数字,除非它们紧跟“#”字符。有很多关于在字符后删除部分字符串的帖子,但我只想保留某个字符后面的数字,直到下一个空格。上面的示例字符串应该是这样的......

   $string = 'Example words #25 more words';
   $string2 = 'Sample words Example words #25 more words #26';

是否可以?这可以用正则表达式完成吗?如何修改以下代码片段来完成此操作?

  $string = preg_replace('/[0-9]+/', '', $string);

标签: phpregexstring

解决方案


您可以使用单词边界和否定的lookbehind的组合来表示“捕获任何前面没有#的数字集”:

$string = preg_replace('/\b(?<!#)(\d+)/', '', $string);

如果您还想删除数字后的空格:

$string = preg_replace('/\b(?<!#)(\d+\s)/', '', $string);

示例:https ://www.phpliveregex.com/p/psK


推荐阅读