PHP使用正则表达式将markdown类似语法转换为图像HTML标记

时间:2013-12-04 21:50:33

标签: php html regex

我正在创建一些类似于Markdown的语法。尝试转换以下语法,无论冒号,属性关键字,属性值或parentesis之间的间距(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正确选择它们。

谢谢!

1 个答案:

答案 0 :(得分:0)

查看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的其余部分将包含你需要的字符串。