php - 如何使用正则表达式和 php 向特定单词添加附加标签

标签 php regex

我想添加到#indlude。即如果

#include<stdio.h> 
#include<math.h>
int main() 

是我的目标字符串,那么它将是:

  <span class="header">#include<stdio.h></span>
  <span class="header">#include<math.h></span>
  int main() 

我尝试使用正则表达式如下:

<?php 
$input = '#include<stdio.h> int main()';
$input = preg_replace('/(#(\w)+<(\w)+.h>)/','<span class="header">$1</span>',$input);

echo $input;
?>

但运气不佳。有什么想法吗?

最佳答案

除非您另有说明,否则您不需要任何捕获组或行起始 anchor ;只需替换全字符串匹配( $0 )

代码:(Demo)

$string = <<<STRING
#include<math.h>
#include<stdio.h>

int main()
STRING;

echo preg_replace('~#include<[^>]+>~', '<span class="header">$0</span>', $string);

输出:

<span class="header">#include<math.h></span>
<span class="header">#include<stdio.h></span>

int main()

否定字符类 ( [^>] ) 将贪婪地匹配 < 之间的所有字符和> -- 就模式效率而言,这是更可取的。

关于php - 如何使用正则表达式和 php 向特定单词添加附加标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53470113/

相关文章:

php - Laravel 5.2.31 Socialite 证书 ssl 错误

php - mysql响应中的波兰字符

php - Mysql:基于数组的多对多查询

php - 仍然显示相同的错误: cURL error 60: SSL certificate problem: unable to get local issuer certificate

php - 需要存储多个日期范围值并通过 sql 检索它们

python - 从数据框中的字符串中提取第一个日期

c# - 在整个文件中进行多行正则表达式搜索

python - 如何使用 Python 在数据框中查找字符串匹配项

javascript - 使用正则表达式匹配多个 url 路径,包括正斜杠

javascript - 如何检测 "stylized"文本?