如何使用PHP替换基于表达式的段落中的字符串

时间:2016-04-27 12:12:13

标签: php

这里我有一个示例段落$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';

根据$input_str替换段落内容$control_name

 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字符串函数。 如何使用字符串函数或其他方法。 谢谢大家。

4 个答案:

答案 0 :(得分:3)

$string = preg_match('~/(.*?)]~', $input_str, $output);

答案 1 :(得分:2)

我的解决方案是将$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

答案 2 :(得分:0)

//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

如果这对您有用,请告诉我。

答案 3 :(得分:0)

这样的正则表达式从你的字符串中获取无线电的名称和值。 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);

demo