2013-05-09 43 views
-5

我已經在互聯網上找到這段代碼...我真的不知道PHP ... 能有人高科技我,pleaase即時通訊pleasee ..PHP的preg_match_all,WordPress的功能

<?php 
function catch_that_image() { 
    global $post, $posts; 
    $first_img = ''; 
    ob_start(); 
    ob_end_clean(); 
    $output = preg_match_all('<img.+src=[\'"]([^\'"]+)[\'"].*>', $post->post_content, $matches); 
    $first_img = $matches [1] [0]; 

    if(empty($first_img)){ //Defines a default image 
    $first_img = "/images/default.jpg"; 
    } 
    return $first_img; 
} 
?> 

如何更換<img.+src=[\'"]([^\'"]+)[\'"].*>

如果我想採取後 「=」 和 「]」 這個文本前字:

[image name=ubuntustudio-tribal-54] 
or 
[image name=office-tool] 
or 
[image name=car] 
or 
[image name=158] 

我想輸出TAKE 「AZ或符號或數字」 AFTER THIS「=」,並在此之前,「]」

感謝

+1

怎麼樣教你自己? – hek2mgl 2013-05-09 20:19:11

+0

不知道我明白了。你的圖片是簡碼還是發生了什麼?爲什麼你會在post_content中用方括號包裝圖像?如果它是正確的HTML,我建議使用DOMDocument,而不是正則表達式。 – adeneo 2013-05-09 20:20:21

+3

當我沒有能力做任務時,我僱用了一個。 – 2013-05-09 20:21:06

回答

1

你在互聯網上找到的代碼是那種無關。爲了達到你想要什麼,你需要這樣的:

$str = "[image name=ubuntustudio-tribal-54] "; 
$pat = "~\[image name=([^\]]+)~i"; 
preg_match($pat, $str, $matches); 
$name = $matches[1]; 

之後$name將被綁定到ubuntustudio-tribal-54

有關PHP的更多詳情,請參閱文檔preg_match
另請參見,關於Regular Expressions的一般信息的重要來源。

+0

不知道爲什麼你要逃避兩次'\\ ['但是在PCRE for PHP中,你只需要逃脫一次:''[' – HamZa 2013-05-09 20:29:31

+0

感謝專家系統..我做了這個'<?php 函數catch_that_image(){ 全球$ post,$ posts; $ first_img =''; $ str =「[image name = ubuntustudio-tribal-54]」; $ pat =「〜\\ [image name =([^ \\]] +)〜i」; ob_start(); ob_end_clean(); $ output = preg_match($ pat,$ str,$ matches); $ name = $ matches [1];如果(空($ first_img)){//定義默認圖像 $ first_img =「/images/default.jpg」; } return $ name; '但是如何替換$ str =「[image name = ubuntustudio-tribal-54]」; 那麼,這個str從wordpress post得到代碼? – 2013-05-09 20:38:14

+0

@ HamZa DzCyber​​DeV真的,在PCRE for PHP中,你只需要逃脫一次 - 我已經習慣了Java的雙重轉義:)我將盡快從我的答案中刪除雙重逃跑。 Thx指出! – gkalpak 2013-05-09 20:43:05