数组值不适用于preg_replace

时间:2018-06-20 13:31:18

标签: php mysql arrays string

为什么我的代码不起作用?这些示例之间只有一个更改。 我认为$ anchor类型可能有问题吗?

此代码无效:

<?php  
header('Content-Type: text/html; charset=utf-8');
$db = mysql_connect('localhost', 'db_name', 'db_pass'); 
mysql_select_db('db_name'); 
mysql_set_charset('utf8'); 
$res = mysql_query("SELECT * FROM product_description");
while($row = mysql_fetch_array($res)){ 

$anchor = strval($row['description']); //Only this string changed!

    $anchor = preg_replace(
        '@\\<a\\b[^\\>]*\\>(.*?)\\<\\/a\\b[^\\>]*\\>@',
        '\\1',
        $anchor
    );

echo $anchor;

}


mysql_close($db);
?>

但是此代码有效,我在这里只更改了一个字符串:

<?php  
header('Content-Type: text/html; charset=utf-8');
$db = mysql_connect('localhost', 'db_name', 'db_pass'); 
mysql_select_db('db_name'); 
mysql_set_charset('utf8'); 
$res = mysql_query("SELECT * FROM product_description");
while($row = mysql_fetch_array($res)){ 

$anchor = 'Lorem ipsum <a href="http://www.google.es">Google</a> Lorem ipsum <a href="http://www.bing.com">Bing</a>'; //Only this string changed!

    $anchor = preg_replace(
        '@\\<a\\b[^\\>]*\\>(.*?)\\<\\/a\\b[^\\>]*\\>@',
        '\\1',
        $anchor
    );

echo $anchor;

}
mysql_close($db);
?>

1 个答案:

答案 0 :(得分:0)

所以..我解决了我的问题。 只需替换

&quot; to "
&gt; to >
&lt; to <

<?php  
header('Content-Type: text/html; charset=utf-8');
$db = mysql_connect('localhost', 'db_name', 'db_pass'); 
mysql_select_db('db_name'); 
mysql_set_charset('utf8'); 
$res = mysql_query("SELECT * FROM product_description");
while($row = mysql_fetch_array($res)){ 

$anchor = strval($row['description']); //Only this string changed!

// ADD THESE STRINGS START
$anchor = str_replace("&lt;","<",str_replace("&gt;",">",$anchor));
$anchor = str_replace('&quot;', '"', $anchor);
// ADD THESE STRINGS STOP

    $anchor = preg_replace(
        '@\\<a\\b[^\\>]*\\>(.*?)\\<\\/a\\b[^\\>]*\\>@',
        '\\1',
        $anchor
    );

echo $anchor;

}

mysql_close($db);
?>