开发者

Remove numeric prefix from string - PHP regex

开发者 https://www.devze.com 2022-12-22 00:40 出处:网络
Would somebody care to help me out with a regex to reliably recognize and remove any number, followed by a dot, in th开发者_如何学运维e beginning of a string? So that

Would somebody care to help me out with a regex to reliably recognize and remove any number, followed by a dot, in th开发者_如何学运维e beginning of a string? So that

1. Introduction

becomes

Introduction

and

1290394958595. Appendix A

becomes

Appendix A


Try:

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

Which gives:

php > print_r(preg_replace('/^[0-9]+\. +/', '', '1231241. dfg'));
dfg


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


Voilà:

^[0-9]+\.


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.


Stuff after string

$string = "1290394958595. Appendix A";
$first_space_position = strpos(" ", $string);
$stuff_after_space = substr($string, $first_space_position);

Stuff after dot

$string = "1290394958595. Appendix A";
$first_dot_position = strpos(".", $string);
$stuff_after_dot = substr($string, $first_dot_position);


print preg_replace('%^(\d+\. )%', '', '1290394958595. Appendix A');


The PHP function to search a string for a regular expression and to replace that with something else is preg_replace. In this case you want something like:

$mytitle = preg_replace('/^[0-9]+\. */', '', $myline);


Here you go:

/[0-9]+\./

Btw, I'd definitely use a regular expression here as they are very reliable and lightweight.

Cheers


$str="1290394958595. Appendix A";
$s = explode(" ",$str,2);
if( $s[0] + 0 == $s[0]){
  print $s[1];
}
0

精彩评论

暂无评论...
验证码 换一张
取 消