PHP使用regex将类似markdown的语法转换为图像HTML标记


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的其余部分将具有所需的字符串。