【问题标题】:Highlight function names in a string (PHP)突出显示字符串中的函数名称 (PHP)
【发布时间】:2018-04-06 12:11:55
【问题描述】:

有谁知道,如何在包含代码的字符串中突出显示函数名?

例如,我必须遵循以下字符串:

$text = "t <- ind.t.test$statistic[[1]
df <- ind.t.test$parameter[[1]]
r <- sqrt(t^2/(t^2+df))
round(r)";

现在我想用

替换函数 sqrt()
<font color='red'>sqrt</font>(t^2...

我已经尝试过:- preg_replace(),

但没能做对。

谢谢!

【问题讨论】:

  • preg_replace()展示你的尝试
  • preg_replace('/(sqrt|round)/', '&lt;span class="highlight"&gt;\0&lt;/span&gt;', $text); 然后为.highlight添加一个css类
  • 谢谢您的帮助!问题是,它不仅适用于上面字符串中提到的函数(sqrt,round),而且适用于 any 函数名称。
  • 您可以添加任意数量的内容,只需保持管道分隔它们,或者尝试找到一个库,无论使用哪种语言都可以为您执行此操作
  • 这是一个非常幼稚的尝试...preg_replace('/(\w+)\(/', '&lt;span class="highlight"&gt;\1&lt;/span&gt;', $text);

标签: php preg-replace syntax-highlighting


【解决方案1】:

试一试。凭票。

$text = "t <- ind.t.test$statistic[[1]
df <- ind.t.test$parameter[[1]]
r <- sqrt(t^2/(t^2+df))
round(r)";

$st2="<font color='red'>sqrt</font>(t^2...";
$match= preg_replace("/\s(\w+)\S(?=\()/",$st2,$text);
echo $match;
;

【讨论】:

    猜你喜欢
    • 2022-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-21
    • 2015-06-24
    • 2012-09-09
    相关资源
    最近更新 更多