Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove numeric prefix from string - PHP regex

Tags:

regex

php

Would somebody care to help me out with a regex to reliably recognize and remove any number, followed by a dot, in the beginning of a string? So that

1. Introduction

becomes

Introduction

and

1290394958595. Appendix A

becomes

Appendix A
like image 426
Pekka Avatar asked Mar 07 '10 22:03

Pekka


4 Answers

Try:

preg_replace('/^[0-9]+\. +/', '', $string);

Which gives:

php > print_r(preg_replace('/^[0-9]+\. +/', '', '1231241. dfg'));
dfg
like image 79
2 revs Avatar answered Nov 10 '22 03:11

2 revs


I know the question is closed, just my two cents:

preg_replace("/^[0-9\\.\\s]+/", "", "1234. Appendix A");

Would work best, in my opinion, mainly because It will also handle cases such as

1.2 This is a level-two heading
like image 27
Felix Avatar answered Nov 10 '22 01:11

Felix


Voilà:

^[0-9]+\.
like image 35
Romain Avatar answered Nov 10 '22 01:11

Romain


Ok, this does not qualify for recognize and remove any number, followed by a dot, but it will return the desired string, e.g. Appendix A, so it might qualify as an alternative.

// remove everything before first space
echo trim(strstr('1290394958595. Appendix A', ' '));

// remove all numbers and dot and space from the left side of string
echo ltrim('1290394958595. Appendix A', '0123456789. ');

Just disregard it, it it's not an option.

like image 39
Gordon Avatar answered Nov 10 '22 02:11

Gordon