用 PHP 正则表达式替换字符串开头的数字、破折号、点或空格 [英] Replace numbers, dash, dot or space from the start of a string with PHP regex

查看:42
本文介绍了用 PHP 正则表达式替换字符串开头的数字、破折号、点或空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

PHP
HTML5
CSS3

我的代码如下:

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

推荐答案

你的正则表达式 - /^[\d{0,4}(. -)?]/ - 匹配字符串,然后是 1 个字符:一个数字,或者一个 {,或者一个 0,或者一个 ,,或},或(,或点,或从空格到)(即空格,!"#$%&') 或问号.因此,它只能在您描述的有限数量的情况下起作用.

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.

随便用

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

这里,

  • ^ - 匹配字符串/行的开头
  • [\d .-]+ 匹配一个数字、空格、点或连字符,1 次或多次 d
  • ^ - matches beginning of string/line
  • [\d .-]+ matches a digit, space, dot or hyphen, 1 or more timesd

参见演示

请注意,如果您有多行,则需要 (?m) 修饰符.

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

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

这是一个 IDEONE 演示

注意:如果您打算从字符串开头删除任何不是字母的内容,我建议使用 ^\P{L}+ regex 带有 u 修饰符.

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.

这篇关于用 PHP 正则表达式替换字符串开头的数字、破折号、点或空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆