smarttechy smarttechy - 2 months ago 8
PHP Question

How to replace % symbol from a string?

foreach($data_features as $feature){
echo $feature['feature'].'<br>'; //string contains % symbol
$featur = str_replace("%", "'", $feature['feature']);
$featur = str_replace("!", '"', $feature['feature']);
echo '<li>'.$featur.'</li>'; // string still contains % symbol.
}


Here $feature['feature'] is a string that contains % symbol and I want to replace the % symbol using str_replace however % symbol is still present in the output.

Answer

This may helps you:-

<?php 
    error_reporting(E_ALL);
    ini_set('display_errors',1);
    $data_features =  Array ( 
    '0' => Array ( 
            'id' => 1, 
            'product_id' => 1, 
            'feature' => 'Customisation-With an open OS, you%re in control.', 
            'time_added' => '2016-09-28 15:33:28',
            'product_asin' => 'B014UUQUAO' 
        ), 
    '1' => Array ( 
            'id' => 2, 
            'product_id' => 1, 
            'feature' => 'Enhanced Expirences- We believe core experiences like audio, email, and calling can be better. That%s we%re re.', 
            'time_added' => '2016-09-28 15:33:28', 
            'product_asin' => 'B014UUQUAO'
        ),
    '2' => Array ( 
            'id' => 3, 
            'product_id' => 1, 
            'feature' => 'Privacy & Securitye.', 
            'time_added' => '2016-09-28 15:33:28', 
            'product_asin' => 'B014UUQUAO' 
        ) 
 );

echo "<pre/>";print_r($data_features);
foreach($data_features as $feature){
    $featur = $feature['feature'];
    $find = array('/%/', '/!/');
    $replace = array("'", '"');
    $result = preg_replace($find, $replace, $feature['feature']);

    echo '<li>'.$result.'</li>';
}
?>

output:-https://eval.in/651753

Note:-

Instead of multiple str_replace(), Single preg_replace() with $find and $replace array is good idea.

In near future if some more replecement needed then only change in $find and $replace will needed.

Comments