PHP 處理字符串的代碼片段

移除html 標籤:

$text = strip_tags($input, "");

返回 $start 和 $end 之間的文本

function GetBetween($content,$start,$end){
    $r = explode($start, $content);
    if (isset($r[1])){
        $r = explode($end, $r[1]);
        return $r[0];
    }
    return '';
}

將字符串中的url 轉換成鏈接:

$url = "Jean-Baptiste Jung (http://www.webdevcat.com)";
$url = preg_replace("#http://([A-z0-9./-]+)#", '<a href="http://www.catswhocode.com/blog/$1" style="font-size: 12px; vertical-align: baseline; background-color: transparent; margin: 0px; padding: 0px; color: #3777af; text-decoration: none; font-weight: bold">$0</a>', $url);

刪除字符串中的URL:

$string = preg_replace('/\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|$!:,.;]*[A-Z0-9+&@#\/%=~_|$]/i', '', $string);

解析CSV文件:

$fh = fopen("contacts.csv", "r");
while($line = fgetcsv($fh, 1000, ",")) {
    echo "Contact: {$line[1]}";
}

字符串搜索:

function contains($str, $content, $ignorecase=true){
    if ($ignorecase){
        $str = strtolower($str);
        $content = strtolower($content);
    }
    return strpos($content,$str) ? true : false;
}

從字符串中提取 email 地址:

function extract_emails($str){
    // This regular expression extracts all emails from a string:
    $regexp = '/([a-z0-9_\.\-])+\@(([a-z0-9\-])+\.)+([a-z0-9]{2,4})+/i';
    preg_match_all($regexp, $str, $m);

    return isset($m[0]) ? $m[0] : array();
}

$test_string = 'This is a test string...

        [email protected]

        Test different formats:
        [email protected];
        <a href="[email protected]">foobar</a>
        <[email protected]>

        strange formats:
        [email protected]
        test6[at]example.org
        [email protected]
        test8@ example.org
        test9@!foo!.org

        foobar
';

print_r(extract_emails($test_string));


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章