替换php字符串的某些部分

时间:2013-04-19 20:43:57

标签: php

我有一些文字(在此特定情况下为$expression,有时会很长。我希望以与输出numbers %粗体相同的方式输出文本。有时拼写为3%,有时会有123 %这样的空格。

<?php
$expression = 'here we got a number 23 % and so on';
$tokens = "([0-9]+)[:space:]([\%])";
$pattern = '/[0-9][0-9] %/';

$keyword = array($pattern);
$replacement = array("<b>$keyword</b>");
echo preg_replace($keyword, $replacement, $expression);
?>

这就是我所拥有的,但我不确定我做错了什么。它会在行$replacement = array("<b>$keyword</b>");上输出错误,然后输出实际字符串,但它会将number%替换为<b>Array</b>

3 个答案:

答案 0 :(得分:2)

您面对(不需要的)数组到字符串转换。在开发过程中,总是可以看到警告/通知,PHP会告诉您这种情况发生(以及在哪里)。

再次查看preg_replace manual page,它会显示替换的正确语法。请特别关注替换参数中关于反向引用的部分。

$replacement = array("<b>\\0</b>");

答案 1 :(得分:2)

试试这个

$expression = 'here we got a number 23 % and so on';
var_dump(preg_replace('/(\d+\s*\%)/', "<b>$1</b>", $expression));

答案 2 :(得分:0)

您的模式和替换是错误的,您需要模式中的一个组才能在替换中使用“变量”占位符。查看preg_replace manual了解详情。

我使用解决方案创建了这个gist,代码就在其中:

<?php

$expression = 'here we got a number 23 % and so on';
$pattern = '/(\d+ %)/';
$replacement = '<b>$1</b>';
echo preg_replace($pattern, $replacement, $expression);