簡體   English   中英

PHP 正則表達式,從文本中提取所有自定義標簽

[英]PHP Regex, extract all custom tags from text

簡單地說,我需要從一段文本中提取所有用花括號括起來的字符串,如

這是一個{tag},但這里也是{tag_2},然后又是...{tag_3}...這里但周圍有一些垃圾。

我想得到一個標簽數組,tag_2 和 tag_3。 標簽只能有單詞字符。

我試過這個:

$tags = array();
preg_match_all("/\{\w+\}/s", $data['text'], $tags);

如果在上述文本片段上運行,則標簽數組返回空。

編輯:

給大家帶來的麻煩,我深表歉意,后來發現我搞砸了。 我通過 $tags 而不是 $tags[0] 捕獲標簽,因此我的合並數組始終為空。

它工作正常:

<?php
$text = 'Here is a {tag}, but here {tag_2} as well, and then again ...{tag_3}... here but with some trash around it.';
$tags = array();
preg_match_all("/\{\w+\}/s", $text, $tags);
print_r($tags);
?>

產生:

Array
(
    [0] => Array
        (
            [0] => {tag}
            [1] => {tag_2}
            [2] => {tag_3}
        )

)

你的$data['text']可能是空的。

Ideone測試。

可能如果您在正則表達式中缺少(可選)下划線:

$tags = array();
preg_match_all("/\{[a-z]+(?:_[1-9][0-9]*)?\}/s", $data['text'], $tags);

您的正則表達式並非如此,因為\w包含下划線。 為下面的評論留下問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM