Welcome to WebmasterWorld Guest from 54.211.136.250

Forum Moderators: coopster & jatar k

Message Too Old, No Replies

Regex Remove Non-Alphabetical characters from beginning of string

   
12:05 am on Sep 13, 2013 (gmt 0)

5+ Year Member



I am trying remove any characters from the beginning of the string, except for letters A-Z and a-z. In other words, I need to make sure that the string begins with a letter.

Regular Expressions are not my strength by any stretch of the imagination, but here's what I've managed to hack up so far.

$str = preg_replace( "/^[^A-Za-z]*/", '', $str );


For some reason it isn't removing the characters. Any thoughts?
12:13 am on Sep 13, 2013 (gmt 0)

WebmasterWorld Senior Member Top Contributors Of The Month



You're really close to having it working.

* = 0 or more of the preceding
+ = 1 or more of the preceding

With the negative match you need to check for 1 or more characters not a-z.

<?php

$str="123abc";
$str = preg_replace( "/^[^A-Za-z]+/", '', $str );
echo $str;

echo '<br>';

$str="abc1def";
$str = preg_replace( "/^[^A-Za-z]+/", '', $str );
echo $str;

?>
12:24 am on Sep 13, 2013 (gmt 0)

5+ Year Member



Thanks for the reply! Even using + it is still not removing the characters I need it to remove. In this particular case, the string begins with "16:13 (3)"
12:28 am on Sep 13, 2013 (gmt 0)

WebmasterWorld Senior Member Top Contributors Of The Month



Try emptying your cache [especially if you're using IE], because even when I drop the characters you provided in I'm getting the correct string.

Here's some more tests I just ran to make sure.

<?php

$str="16:13 (3) 123abc";
$str = preg_replace( "/^[^A-Za-z]+/", '', $str );
echo $str;

echo '<br>';

$str="16:13a(3)b123abc";
$str = preg_replace( "/^[^A-Za-z]+/", '', $str );
echo $str;

echo '<br>';

$str="abc1def";
$str = preg_replace( "/^[^A-Za-z]+/", '', $str );
echo $str;

?>

/test.php results:
abc
a(3)b123abc
abc1def

[edited by: JD_Toims at 12:29 am (utc) on Sep 13, 2013]

12:29 am on Sep 13, 2013 (gmt 0)

5+ Year Member



Disregard my last! I found the problem to be elsewhere in the code. Your suggestion of the + instead of * worked! Thank you so much for your help. Hopefully one of these days I'll get around to learning regex myself.
12:32 am on Sep 13, 2013 (gmt 0)

WebmasterWorld Senior Member Top Contributors Of The Month



Glad you got it sorted out!

Regexes take quite a while to learn -- I've been writing them for years and still find areas I can improve in, so I totally understand being too time-challenged to get to them and really sit down and figure out what makes them tick. It's tough enough to keep up with everything else for a site, so glad I could help!