Rama Lingam Rama Lingam - 7 months ago 15
PHP Question

How to replace the string in a paragraph based on expression using PHP

Here I have a sample paragraph

$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';


Replace the paragraph content
$input_str
based on
$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';
}


Really I don't know the PHP string function.
How to do by using string functions or other ways.
Thanks to all.

Answer

My solution is to split the $input_str into 3 parts, before, controller and after. Then we use a switch based on the $control_name and lastly we match the text associated with that controller and put together the pieces, i.e.:

<?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";

The above code should work with any $input_str as long as the pattern is the same, some text... [ controller: some text ending with. ] more text...


IdeoneDemo