数组值不能与preg\u replace一起使用

c3frrgcw  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(377)

为什么我的代码不起作用?这些例子之间只有一个变化。我想可能是$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);
?>
qc6wkl3g

qc6wkl3g1#

所以。。我解决了我的问题。只要替换一下

&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);
?>

相关问题