[英]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.