Junius L
Junius L

Reputation: 16142

Replace numbers, dash, dot or space from the start of a string with PHP regex

I'm trying to replace numbers with optional, dash, dot or space from the start of a string, my pattern does not seem to work. I want to replace this:

01. PHP
02  HTML5
03. - CSS3

with

PHP
HTML5
CSS3

My code is below:

$t = trim($_POST['test']);
$pattern = '/^[\d{0,4}(. -)?]/';
if(preg_match($pattern, $t)){
    echo preg_replace($pattern,'', $t);
}else{
    echo 'No';
}

Upvotes: 2

Views: 6351

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627082

Your regex - /^[\d{0,4}(. -)?]/ - matches the beginning of the string, and then 1 character: either a digit, or a {, or a 0, or a ,, or a }, or a (, or a dot, or a range from space to ) (i.e. a space, !"#$%&' and a ), or a question mark. So, it can only work in a limited number of case you describe.

Just use

preg_replace('/^[\d .-]+/','', $t);

Here,

  • ^ - matches beginning of string/line
  • [\d .-]+ matches a digit, space, dot or hyphen, 1 or more timesd

See demo

Nogte that if you have multiple lines, you need (?m) modifier.

preg_replace('/(?m)^[\d .-]+/','', $t);

Here is an IDEONE demo

NOTE: If you plan to remove anything that is not letter from the beginning of the string, I'd recommend using ^\P{L}+ regex with u modifier.

Upvotes: 5

MH2K9
MH2K9

Reputation: 12039

Can try this

$t = "01. PHP";

$pattern = '/^[0-9\.\s\-]+/';

echo preg_replace($pattern, '', $t);

Output

PHP

Regex Explanation

^ assert position at start of the string
0-9 a single character in the range between 0 and 9
\. matches the character . literally
\s match any white space character [\r\n\t\f ]
\- matches the character - literally

Upvotes: 1

Related Questions