something wrong with preg_replace?


something wrong with preg_replace?

设法使用preg_match_all后,我想用匹配的文本替换匹配的文本,但它似乎不起作用。看看我的代码,我做错了什么?

    <?php
    $tweets = getTweets($profile->twitter_id);
    for($i=0;$i<4;$i++):
        // finds matches
        $num_matches = preg_match_all('/@'w+/', $tweets[$i]->description, $matches);
        if($num_matches):
            echo $num_matches.'<br />';
            for($c=0;$c<$num_matches;$c++):
                $subject = $tweets[$i]->description;
                $pattern = array();
                $pattern[$c] = $matches[0][$c];
                $replacement = array();
                $replacement[$c] = '<a href="https://twitter.com/#!/">'.$matches[0][$c].'</a>';
            endfor;
                echo preg_replace($pattern, $replacement, $subject).'<br /><br />';
        else:
            echo auto_link($tweets[$i]->description).'<br /><br />';
        endif;
    endfor;
?>
你需要

在循环之外定义$pattern$replacement,否则它们将在每次迭代时重新初始化为空数组:

$pattern = array(); $replacement = array();
for($c=0;$c<$num_matches;$c++):

也许,你的preg_replace不使用模式:$matches[0][$c]包含一个字符串,而不是一个带有分隔符的模式。话又说回来,我可能是错的。查看您的匹配项以及要替换的内容可能会有所帮助

,我简直不敢相信我也忽略了循环内的数组声明......当然,这是您应该修复的第一件事!

谢谢你们的回答,但是我停止使用preg_replace,而是使用str_replace。它工作正常。这是我的最终代码。

    <?php
        $tweets = getTweets($profile->twitter_id);
        for($i=0;$i<4;$i++):
            // first, explode the description to eliminate the username in the description
            $tweet_des = $tweets[$i]->description;
            $tweet_no_username_des = explode(':',$tweet_des,2); // added a limit parameter, ensuring only the username will be excluded
            $new_tweet_description = $tweet_no_username_des[1].'<br />';
            // the date the tweet is published
            echo $date_pub = $tweets[$i]->pubDate;
            // using preg_match_all to find matches, texts having '@' as the first letter
            $num_matches = preg_match_all('/@'w+/', $tweets[$i]->description, $matches);
            if($num_matches):   // if match(es) are found
                $search_arr = array();  // declared an array to contain the search parameter for str_replace
                $replace_arr = array(); // declared an array to contain the replace parameter for str_replace
                for($c=0;$c<$num_matches;$c++):
                    $search_arr[$c] = $matches[0][$c];
                    $name_links[$c] = explode('@',$search_arr[$c]);
                    $not_link_name = $name_links[$c][1];
                    $replace_arr[$c] = '<a href="http://twitter.com/#!/'.$not_link_name.'" target="_blank">'.$matches[0][$c].'</a>';
                endfor;
                echo auto_link(str_replace($search_arr, $replace_arr, $new_tweet_description)).'<br />';
            else:
                echo auto_link($new_tweet_description).'<br />';
            endif;
        endfor;
    ?>

最初,我的问题是找到以"@"开头的文本,并将其链接到Twitter中的相应帐户。请随时批评我的代码,我认为它仍然有问题。:)