Detecting emails in a text

前端 未结 4 987
生来不讨喜
生来不讨喜 2020-12-31 05:52

I\'m trying to create a function that translates every occurrence of a plain text email address in a given string into it\'s htmlized version.

Let\'s say I h

4条回答
  •  执笔经年
    2020-12-31 06:43

    The code below should work fine, but it regex is easier to go with.

    $str = "Send me an email to bob@example.com.";
    
       function htmlizestring($a){
    
            if(substr_count($a,"@") != 1){
                return false;
            }else{
                $b4 = stristr($a,"@",true);
                $b4pos = strripos($b4," ")+1;
                $b4 = trim(substr($b4,$b4pos));
                $after = stristr($a,"@");           
                if(substr_count($after, " ") == 0){
                    $after=rtrim($after," .,");
                }else{
                    $after=trim(stristr($after," ",true));
                }
                $email = $b4.$after;
                echo $email;
                if(filter_var($email, FILTER_VALIDATE_EMAIL)){
                    echo "Send me an email at: ".$email."";
                }else{
                    return false;
                }
            }   
    
        }
    
        htmlizestring($str);
    

    I happen to use stristr() with the third parameter TRUE, which only works on php 5.3+

提交回复
热议问题