[英]PHP using regex to convert markdown similar syntax into image HTML tag
我正在創建一些類似於Markdown的語法。 無論冒號,屬性關鍵字,屬性值或括號之間的間距如何,都嘗試轉換以下語法(alt和class屬性的順序無關緊要):
(image: profile.jpg alt: Michael class: profile)
(image : profile.jpg alt : Michael class : profile)
( image : profile.jpg alt : Michael class : profile )
全部正確地放入img標簽
<img src="profile.jpg" alt="Michael" class="profile">
並非總是使用alt和class標簽屬性,因此例如
(image: profile.jpg class: profile)
會變成
<img src="profile.jpg" class="profile">
和以下
(image: profile.jpg)
會變成
<img src="profile.jpg">
但有時類值(或alt值)由多個單詞組成,例如
(image: profile.jpg alt: Michael Jackson class: profile dark red)
並且應該成為
<img src="profile.jpg" alt="Michael Jackson" class="profile dark red">
我嘗試這樣做,但是由於屬性關鍵字和值之間的空格而失敗,不知道如何正確使用preg_match()和/或preg_replace選擇它們。
謝謝!
看一下preg_split函數,以及可以包含的PREG_SPLIT_DELIM_CAPTURE
標志。 例如,如果輸入的每一行都是$line
,並且括號被去除了:
$pieces = preg_split('/(\S+)\s*:/', $line, -1, PREG_SPLIT_DELIM_CAPTURE);
$pieces
將是這樣的數組:
array (
0 => '',
1 => 'image',
2 => ' profile.jpg ',
3 => 'alt',
4 => ' Michael Jackson ',
5 => 'class',
6 => ' profile dark red',
)
由於PHP的某些缺陷,您必須扔掉第0個元素,但是$pieces
的其余$pieces
將具有您需要的字符串。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.