Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/262.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP正则表达式将span添加到文本字符串匹配_Php_Regex - Fatal编程技术网

PHP正则表达式将span添加到文本字符串匹配

PHP正则表达式将span添加到文本字符串匹配,php,regex,Php,Regex,我有以下代码: if (preg_match('/^[A-Z]\./', $element['#title'])) { $element['#title'] = preg_replace('/^[A-Z]\./', '<span>$0</span>', $element['#title']); } if(预匹配('/^[A-Z]\./',$element['.\title'])){ $element['#title']=preg_replace('/^[A-Z]\.

我有以下代码:

if (preg_match('/^[A-Z]\./', $element['#title'])) {
  $element['#title'] = preg_replace('/^[A-Z]\./', '<span>$0</span>', $element['#title']);
}
if(预匹配('/^[A-Z]\./',$element['.\title'])){
$element['#title']=preg_replace('/^[A-Z]\./','$0',$element['#title']);
}
这将添加一个范围标记,例如

<span>A.</span> This is a title
A.这是一个标题
我现在有几个字符串要匹配,它们是:

[A-Z]

[A-Z].[1-99]

[A-Z].[1-99].[1-99]

[A-Z].[1-99].[1-99].[1-99]

Regex不是我的强项!有人能帮忙吗

谢谢

史蒂夫

你可以用这个

^[A-Z]\.(?>[0-9]++\.?+)*
请注意,之前不需要使用preg_match进行测试,因为preg_replace仅在发现以下内容时才进行替换:

$element['#title'] = preg_replace('~^[A-Z]\.(?>[0-9]{1,2}\.?+)*~', '<span>$0</span>', $element['#title']);
$element['#title']=preg_replace('~^[A-Z]\.(?>[0-9]{1,2}\.?+)*~'、'$0'、$element['#title']);

基本上,您首先匹配大写字母,然后是句点;然后,可以在数字之后出现零到三次,然后出现一个句点:

/^[A-Z]\.(?:\d+\.){0,3}/

超级快速响应!谢谢奇怪的是这不起作用?根据您的回复,我删除了if声明。我把事情弄糊涂了吗?示例字符串模式可能是A.或B.2或Z.32。4@StephenWilson:在您在问题中给出的示例字符串中,末尾始终有一个点。我已经编辑了我的模式,使其成为可选模式。对不起,我又把你弄糊涂了。文本字符串的末尾总是有一个点,后面跟着一些文本,例如
a.1.99。此处有一些文本
B.99。此处有更多文字
@StephenWilson:删除端锚
$
效果完美。真希望我能在regex周围转一转!非常感谢你。汉克斯·杰克。卡西米尔帮我解决了问题,但谢谢你的回复。S@StephenWilson没问题;我觉得这个表达式不那么复杂,难以理解:)