简体   繁体   English

php正则表达式匹配和替换

[英]php regular expression matches and replacement

again. 再次。 I'm trying to go through a database table and replace all instances of old BBCode (ie: [i:fs8d979] ) and replace it with simple BBCode ( [i] ). 我正在尝试通过数据库表并替换旧BBCode的所有实例(即: [i:fs8d979] )并将其替换为简单的BBCode( [i] )。 However, I'm getting very confusing results. 但是,我的结果非常混乱。

$root_path = './';
include($root_path.'includes/common.php');

$posts = array();
$sql = 'SELECT post_id, post_text FROM posts';
$db->query($sql);
while($row = $db->fetch_assoc())
{
    $posts[]['id'] = $row['post_id'];
    $posts[]['text'] = $row['post_text'];
}

foreach($posts as $post)
{
    $regex = "/\[(\D)(\:[a-zA-Z0-9_]{1,})\]/";

    if(preg_match($regex, $post['text'], $matches))
    {
        $string = preg_replace('/'.$matches[2].'/', '', $post['text']);
        $sql = 'UPDATE posts SET post_text = "'.$string.'" WHERE post_id = '.$post['id'];
        $db->query($sql);
        echo $post['id'].'--Matched and replaced<br />';
    }
    else
    {
        echo $post['id'].'--No Match<br />';
    }
}
echo 'done';

when i run this script, I get output like this: 当我运行这个脚本时,我得到这样的输出:

1302--No Match
--No Match
1303--No Match
--No Match
17305--No Match
--Matched and replaced
5532--No Match
--No Match
17304--No Match
--No Match
1310--No Match
--No Match

it would appear that the script is attempting to do everything twice, and I'm not sure why. 似乎脚本试图做两次所有事情,我不知道为什么。 The database fields are not getting updated either. 数据库字段也未更新。 I've echoed everything out for debugging purposes, and all variables are set and everything looks like it should be working properly. 为了调试的目的,我已经回应了所有的东西,所有的变量都设置好了,一切看起来都应该正常工作。 Any suggestions? 有什么建议么?

At the point in the code: 在代码中的点:

while($row = $db->fetch_assoc())
{
    $posts[]['id'] = $row['post_id'];
    $posts[]['text'] = $row['post_text'];
}

You are creating two entries in the array, one with the id, followed by the text. 您正在数组中创建两个条目,一个具有id,后跟文本。

I think you want: 我想你想要:

while($row = $db->fetch_assoc())
{
    $posts[] = array('id' => $row['post_id'], 'text' => $row['post_text']);
}

It would explain why each one is happening twice and nothing is changing. 它可以解释为什么每一个都发生两次而且没有任何变化。

The debug was showing the wrong value too: 调试也显示错误的值:

echo $post['id'].'--Matched and replaced<br />';

and the output was 而输出是

--Matched and replaced which showed no post id. --Matched and replaced ,显示没有帖子ID。

First: the lines 第一:行

$posts[]['id'] = $row['post_id'];
$posts[]['text'] = $row['post_text'];

are adding two elements to the $posts array. 正在向$posts数组添加两个元素。 That is why you are getting two outputs per post. 这就是为什么你每个帖子得到两个输出。

Second: I don't think the colon : is a special character - it doesn't need to be escaped. 第二:我不认为冒号:是一个特殊的角色 - 它不需要逃脱。 So it should look like: 所以看起来应该是这样的:

$regex = "/\[(\D)(:[a-zA-Z0-9_]+)\]/";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM