【问题标题】:Array value not working with preg_replace数组值不适用于 preg_replace
【发布时间】:2018-11-29 15:52:36
【问题描述】:

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

【问题讨论】:

  • 这里的 where 子句有什么意义?为什么你用 sql server 标记这个,很明显你使用的是 mysql。但真正的问题是“不起作用”是无用的,因为它不会告诉任何人出了什么问题。
  • var_dump($row)
  • var_dump($row): prntscr.com/jx6iw2
  • mysql_* 函数已在 PHP 7 中删除。您的代码将无法在现代 PHP 安装中运行
  • 您仍然需要更新您的代码以不使用 mysql_* 因为它在 5.6 中已被弃用。它们不能与现代版本的 mysql 一起正常工作,并且多年来一直没有维护。这就是他们在 php 7 中被删除的原因。至少你应该切换到 mysqli

标签: php mysql arrays string


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-17
    • 2016-03-03
    • 1970-01-01
    • 2015-08-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多