php - 从字符串中删除所有数字,除非它们遵循 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);
解决方案
您可以使用单词边界和否定的lookbehind的组合来表示“捕获任何前面没有#的数字集”:
$string = preg_replace('/\b(?<!#)(\d+)/', '', $string);
如果您还想删除数字后的空格:
$string = preg_replace('/\b(?<!#)(\d+\s)/', '', $string);
推荐阅读
- xamarin - 如何:使用 DI/IoC 在 Prism 中管理类似类型的单例
- android-source - 构建aosp时如何设置MAC地址和其他密钥?
- python - 无法访问 div,使用 BeautifulSoup
- .net - Azure Pipelines:任务 PublishBuildArtifacts 避免 zip
- python - 用numpy找到与中位数差异最大的索引
- java - 在 Vaadin Flow 网络应用程序中设置我的“UI”子类的内容
- javascript - Microsoft Edge 中是否有与 window.clipboardData 等效的内容?
- python - 辅助修复 While 循环
- excel - 使用 Excel 验证条目
- android - 错误:com.google.android.gms.internal.measurement.zzdz