gpt4 book ai didi

php - 从字符串中删除所有数字,除非它们跟在 PHP 中的某个字符之后

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:07:30 26 4
gpt4 key购买 nike

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

$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);

最佳答案

您可以结合使用单词边界和负向后视来表示“捕获任何前面没有# 的数字集”:

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

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

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

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

关于php - 从字符串中删除所有数字,除非它们跟在 PHP 中的某个字符之后,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52642815/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com