简体   繁体   English

正则表达式替换到PHP中的特定字符

[英]Regex replace till specific character in php

Let's say I have a strings: 假设我有一个字符串:

a) 'one4two2three1'
b) 'one4two2three1four#five7'

I want to replace all numbers from these strings with empty space ('') - untill '#' character 我想将这些字符串中的所有数字替换为空格('')-直到'#'字符

so final output should be: 因此最终输出应为:

a) 'onetwothree'
b) 'onetwothreefour#five7'

Is there a way to do it with preg_replace(), or any other regex function? 有没有办法用preg_replace()或任何其他正则表达式函数来做到这一点?

I'm trying to avoid an 'if' with strpos() and substr() and find more efficient way 我正在尝试通过strpos()和substr()来避免'if'并找到更有效的方法

You can use PCRE verbs (*SKIP)(*F) to match and discard part after # : 您可以使用PCRE动词(*SKIP)(*F)来匹配和丢弃#之后的部分:

$repl = preg_replace('/#[^#]*$(*SKIP)(*F)|\d+/m', '', $str);

RegEx Demo 正则演示

#[^#]*$(*SKIP)(*F) will match and skip part after # in input and then we can replace all digits by empty string. #[^#]*$(*SKIP)(*F)将匹配并跳过输入中#后面的部分,然后我们可以用空字符串替换所有数字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM