开发者

Lowercase Text Except URL's

开发者 https://www.devze.com 2023-03-17 11:22 出处:网络
I have a page named \"load.php\" whic开发者_StackOverflow社区h is called at the top of every page. It has some various preg_replace() functions, and strtolower() function that affects on $text1 variab

I have a page named "load.php" whic开发者_StackOverflow社区h is called at the top of every page. It has some various preg_replace() functions, and strtolower() function that affects on $text1 variable at the end of the page. (This changes are done while loading the page, not inserting to the db) I want to add a final function before or after the strtolower() to exclude URLs's href attribute from strtolower(). How can i manage this? Thanks.


Let me to try:

//search for links with href
$links = preg_match_all('/href="(?P<link>[^"]*?)"/i',$text1, $matches);
if(count($matches['link'])>0){
    // explode non links pieces of code
    $blocks = preg_split('/href="(?P<link>[^"]*?)"/i',$text1);
    // for assurance
    // non-links pieces should be equal a links plus one
    if(count($matches['link']) == (count($blocks)-1))
    {
        // to lower non-link pieces
        $blocks = array_map("strtolower", $blocks);
        $size = count($matches['link']);
        for($i=0;$i<$size;$i++){
            //putting together the link again without change a case
            $blocks[$i] .= 'href="'.$matches['link'][$i].'"';
        }
        $text1 = join("",$blocks);
    }
} else {
    $text1 = strtolower($text1);
}

Heave a good luck :)


Here you've a shorter version:

function strtolowerExceptLinks($text) {
        $search = '(\b[a-zA-Z0-9]+://[^( |\>\n)]+\b)';
        preg_match_all($search, $text, $matches);
        $urls = array_unique($matches[0]);
        $text = mb_strtolower($text);
        if (is_array($urls)) {
            foreach ($urls as $url) {
                $text = str_replace(mb_strtolower($url), $url, $text);
            }
        }
        return $text;
    }
0

精彩评论

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