这里有一个示例段落$input_str
$input_str = 'Some text is here......[$radio_yes: He is eligible for PF. / $radio_no: He is not eligible for PF.]....Some text is here';
$control_name = 'radio_yes';
根据$control_name
替换段落内容$input_str
。
if($control_name=='radio_yes') Then
{
I want to the result : $result_str = 'Some text is here......He is eligible for PF......Some text is here';
}
else if($control_name=='radio_no') Then
{
I want to the result : $result_str = 'Some text is here......He is not eligible for PF.....Some text is here';
}
真的我不知道PHP字符串函数。如何使用字符串函数或其他方式。谢谢大家。
$string = preg_match('~/(.*?)]~', $input_str, $output);
我的解决方案是将$input_str
分成 3 个部分,之前、控制器和之后。然后我们使用基于最后我们匹配与该$control_name
的开关,controller
关联的文本并将各个部分放在一起,即:
<?php
$input_str = 'Some text is here......[$radio_yes: He is eligible for PF. / $radio_no: He is not eligible for PF.]....Some text is here';
$control_name = 'radio_yes';
preg_match_all('/^(.*?)'[(.*?)'](.*?)$/si', $input_str, $matches, PREG_PATTERN_ORDER);
$before = $matches[1][0];
$controllerRaw = $matches[2][0];
$after = $matches[3][0];
preg_match_all("/$control_name:(.*?)'./si", $controllerRaw, $controller, PREG_PATTERN_ORDER);
$controller = $controller[1][0];
echo "$before $controller $after";
只要模式相同,上面的代码应该适用于任何$input_str
,some text... [ controller: some text ending with. ] more text...
IdeoneDemo
//Your input text;
$input_string = 'Some text is here......[$radio_yes: He is eligible for PF. / $radio_no: He is not eligible for PF.]....Some text is here';
//The text inside the input text you want to be replaced:
$pattern = '/['$radio_yes: He is eligible for PF. / '$radio_no: He is not eligible for PF.]/'
//conditional that decides what the $pattern will be replaced with:
if($control_name=='radio_yes')
{
$replaceWith = 'He is eligible for PF';
}
else($control_name=='radio_no')
{
$replaceWith = 'He is not eligible for PF';
}
//replacing the $pattern and giving the result to $newString
$newString = preg_replace($pattern, $replaceWith, $input_string);
echo $newString;//printing out the results
让我知道这是否适合您。
这样的正则表达式从字符串中获取无线电的名称和值。preg_replace_callback可以通过control_name值来更改它。如果control_name不等于任何找到的值,则返回空字符串
echo preg_replace_callback('~'['$('w+):(.+)/'s*'$('w+):(.+)']~',
function($m) use ($control_name) {
if ($control_name == $m[1])
return $m[2];
if ($control_name == $m[3])
return $m[4];
return "";
},
$input_str);
演示