用PHP正则表达式替换字符串开头的数字、破折号、点或空格


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

我试图从字符串的开始用可选的,破折号,点或空格替换数字,我的模式似乎不起作用。我想替换这个:

01. PHP
02  HTML5
03. - CSS3

PHP
HTML5
CSS3

我的代码如下:

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

您的regex - /^['d{0,4}(. -)?]/ -匹配字符串的开头,然后1个字符:数字,或{,或0,或,,或},或(,或点,或从空格到)(即空格,!"#$%&'))的范围,或问号。所以,它只能在你描述的有限的几种情况下起作用。

只使用

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

,

  • ^ -匹配字符串/行开头
  • ['d .-]+匹配数字,空格,点或连字符,1次或更多时间

看到演示

注意,如果你有多行,你需要(?m)修饰符。

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

这是一个IDEONE演示

注意:如果你打算从字符串的开头删除任何不是字母的东西,我建议使用^'P{L}+ regex和u修饰符。

可以

$t = "01. PHP";
$pattern = '/^[0-9'.'s'-]+/';
echo preg_replace($pattern, '', $t);

PHP

正则表达式解释

^ 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