如何更改(替换)文本中的元素?

时间:2014-04-28 10:57:05

标签: php replace

美好的一天。

我们有代码:

function testfunc($text){
 return $text;
}


$text = "Simple text {testfunc(1)} and next simple text and we {testfunc(20)} are happy ";
// number in {testfunc()} only for example - it can be other number or text.

请告诉我如何在结果函数testfunc($ num)上替换{testfunc(1)}

P.S。:结果需要下一个文字:

$text = "Simple text 1 and next simple text and we 20 are happy ";

5 个答案:

答案 0 :(得分:1)

试试这个:

$newText = preg_replace_callback("/\{testfunc\((\d+)\)\}/","testfunc",$text);

您将在" testfunc"中获得一系列匹配项。对于你想要的,这段代码:

我认为,它可以帮助你。

<?php

function testfunc($text){
    return $text[1];
}


$text = "Simple text {testfunc(1)} and next simple text and we {testfunc(20)} are happy ";
$newText = preg_replace_callback("/\{testfunc\((\d+)\)\}/","testfunc",$text);

echo $text."\n";
echo $newText."\n";
?>

答案 1 :(得分:0)

这应该可以使用字符串连接:

$text = "Simple text " . testfunc(1) . " and next simple text and we " . testfunc(20) . " are happy ";

答案 2 :(得分:0)

尝试

$text = "Simple text ".testfunc(1)." and next simple text and we ".testfunc(20)." are happy ";

答案 3 :(得分:0)

正常情况下为什么不试试,

$text = "Simple text ".testfunc(1)." and next simple text and we ".testfunc(20)." are happy ";

答案 4 :(得分:-1)

<?php
     $text = "Simple text ".testfunc(1)." and next simple text and we ".testfunc(20)." are
happy";
echo $text;
?>