繁体   English   中英

PHP多行正则表达式

[英]PHP Multiline regexp

大家好,我正在尝试为PHP创建一个正则表达式,以使我能够获取报价和作者。 如果一切都是一行,那么我已经使它起作用了,但是当它放到多行中的那一刻它就停止了工作。 我究竟做错了什么?

(\[quote\])(.*)(\|)(.*)(\[\/quote\])

[quote]船坞里的沉默,街道上的沉默,哈根波特的船闸和码头将在您睡觉时抢劫您。|流行的儿童韵律[/ quote]

[quote]让您沉睡。|流行的儿童韵[/ quote]

使用s修饰符 (如果在正则表达式分隔符之后附加)。 另外,通过添加?使您的.*非贪婪?

preg_match_all("~\[quote\](.*?)\|(.*?)\[/quote\]~s", $s, $results,  PREG_SET_ORDER);

输出以$results

[
    [
        "[quote]Silence in the boatyard, Silence in the street, The Locks and Quays of Haganport Will rob you while you sleep.|-popular children's rhyme[/quote]",
        "Silence in the boatyard, Silence in the street, The Locks and Quays of Haganport Will rob you while you sleep.",
        "-popular children's rhyme"
    ], [
        "[quote]Silence you sleep.|-popular children's rhyme[/quote]",
        "Silence you sleep.",
        "-popular children's rhyme"
    ]
]

查看正则表达式在这里使用

\[quote\](.*?)\|-(.*?)\[\/quote\]

注意 :上面的正则表达式使用s修饰符。 或者,您可以替换. [\\s\\S]并禁用s修饰符

用法

$re = '/\[quote\](.*?)\|-(.*?)\[\/quote\]/s';
$str = '[quote]Silence in the boatyard, Silence in the street, The Locks and Quays of Haganport Will rob you while you sleep.|-popular children\'s rhyme[/quote]

[quote]Silence you sleep.|-popular children\'s rhyme[/quote]';

preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);

// Print the entire match result
var_dump($matches);

结果

输入项

[quote]船坞里的沉默,街道上的沉默,哈根波特的船闸和码头将在您睡觉时抢劫您。|流行的儿童韵律[/ quote]

[quote]让您沉睡。|流行的儿童韵[/ quote]

输出量

以下输出按组组织(用换行符分隔)

Silence in the boatyard, Silence in the street, The Locks and Quays of Haganport Will rob you while you sleep.
popular children's rhyme

Silence you sleep.
popular children's rhyme

说明

  • \\[quote\\]逐字匹配(反斜杠转义以下字符)
  • (.*?)多次捕获任何字符,但应尽可能少地捕获到捕获组1中
  • \\|-逐字匹配(反斜杠转义以下字符)
  • (.*?)多次捕获任何字符,但应尽可能少地捕获到捕获组2中
  • \\[\\/quote\\]逐字匹配(反斜杠转义以下字符)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM