user7201963 user7201963 - 17 days ago 9
PHP Question

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

Answer

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.