如何从字符串中替换%符号?

时间:2016-09-28 10:20:34

标签: php str-replace

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.
}

这里$ feature ['feature']是一个包含%符号的字符串,我想用str_replace替换%符号,但输出中仍然存在%符号。

2 个答案:

答案 0 :(得分:1)

我发现我的错误必须放入变量然后应用str_replace操作。不知道原因是什么。

#false

答案 1 :(得分:0)

这可以帮助您: -

<?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>';
}
?>

输出: - https://eval.in/651753

注意: -

而不是多个str_replace(),单preg_replace()$find$replace数组是个好主意。

在不久的将来,如果需要更多补充,则只需更改$find$replace