Reputation: 10552
How would I go about removing numbers and a space from the start of a string?
For example, from '13 Adam Court, Cannock' remove '13 '
Upvotes: 0
Views: 2903
Reputation: 47992
If the input strings all have the same ecpected format and you will receive the same result from left trimming all numbers and spaces (no matter the order of their occurrence at the front of the string), then you don't actually need to fire up the regex engine.
I love regex, but know not to use it unless it provides a valuable advantage over a non-regex technique. Regex is often slower than non-regex techniques.
Use ltrim()
with a character mask that includes spaces and digits.
Code: (Demo)
var_export(
ltrim('420 911 90210 666 keep this part', ' 0..9')
);
Output:
'keep this part'
It wouldn't matter if the string started with a space either. ltrim()
will greedily remove all instances of spaces or numbers from the start of the string intil it can't anymore.
Upvotes: 0
Reputation: 1024
Because everyone else is going the \d+\s route I'll give you the brain-dead answer
$str = preg_replace("#([0-9]+ )#","",$str);
Word to the wise, don't use / as your delimiter in regex, you will experience the dreaded leaning-toothpick-problem when trying to do file paths or something like http://
:)
Upvotes: 3
Reputation: 85468
The same regex I gave you on your other question still applies. You just have to use preg_replace()
instead.
Search for /^[\s\d]+/
and replace with the empty string. Eg:
$str = preg_replace(/^[\s\d]+/, '', $str);
This will remove digits and spaces in any order from the beginning of the string. For something that removes only a number followed by spaces, see BoltClock's answer.
Upvotes: 1
Reputation: 7907
I'd use
/^\d+\s+/
It looks for a number of any size in the beginning of a string ^\d+
Then looks for a patch of whitespace after it \s+
When you use a backslash before certain letters it represents something...
\d
represents a digit 0,1,2,3,4,5,6,7,8,9
.
\s
represents a space .
Add a plus sign (+
) to the end and you can have...
\d+
a series of digits (number)
\s+
multiple spaces (typos etc.)
Upvotes: 2
Reputation: 724172
Use the same regex I gave in my JavaScript answer, but apply it using preg_replace()
:
preg_replace('/^\d+\s+/', '', $str);
Upvotes: 2
Reputation: 93177
Try this one :
^\d+ (.*)$
Like this :
preg_replace ("^\d+ (.*)$", "$1" , $string);
Resources :
On the same topic :
Upvotes: 1