简体   繁体   中英

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?

I'm trying to avoid an 'if' with strpos() and substr() and find more efficient way

You can use PCRE verbs (*SKIP)(*F) to match and discard part after # :

$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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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