开发者

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]). However, I'm getting very confusing results.

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

$posts = array();
$sql = 'SELECT post_id, post_text FROM post开发者_JAVA百科s';
$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.

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.


First: the lines

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

are adding two elements to the $posts array. 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_]+)\]/";
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜