簡體   English   中英

PHP-如何通過空格和html標簽的正則表達式將字符串拆分為數組?

[英]PHP - How to split string into array by regular expression at whitespace and html tag?

這是一個示例字符串:

$string = '<strong>Lorem ipsum dolor</strong> sit <img src="test.png" /> amet <span class="test" style="color:red">consec<i>tet</i>uer</span>.';

我想將字符串拆分為數組,以便每當擊中空白或擊中html標簽時都將字符串拆分(忽略html標簽中的空白)。 例如:

Array
(
    [0] => <strong>
    [1] => Lorem
    [2] => ipsum
    [3] => dolor
    [4] => </strong>
    [5] => sit
    [6] => <img src="test.png" />
    [7] => amet
    [8] => <span class="test" style="color:red">
    [9] => consec
    [10] => <i>
    [11] => tet
    [12] => </i>
    [13] => uer
    [14] => </span>
    [15] => .
)

但我無法實現這一目標。 我用preg_split實現了這個想法,但是我認為我在正則表達式中弄錯了。 下面是我嘗試過的一些表達式,但結果不是我想要的。

$chars = preg_split('/(<[^>]*[^\/]>)/i', $string, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);

/* Results */

Array
(
    [0] => <strong>
    [1] => Lorem ipsum dolor
    [2] => </strong>
    [3] =>  sit <img src="test.png" /> amet 
    [4] => <span class="test" style="color:red">
    [5] => consec
    [6] => <i>
    [7] => tet
    [8] => </i>
    [9] => uer
    [10] => </span>
    [11] => .
)

其他正則表達式的結果是:

$chars = preg_split('/\s+(?![^<>]*>)/x', $string, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);

/* Results */
Array
(
    [0] => <strong>Lorem
    [1] => ipsum
    [2] => dolor</strong>
    [3] => sit
    [4] => <img src="test.png" />
    [5] => amet
    [6] => <span class="test" style="color:red">consec<i>tet</i>uer</span>.
)

並且另一個表達式的結果是(非常接近):

$chars = preg_split('/\s*(<[^>]*>)/i', $string, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);

/* Results */
Array
(
    [0] => <strong>
    [1] => Lorem ipsum dolor
    [2] => </strong>
    [3] =>  sit
    [4] => <img src="test.png" />
    [5] =>  amet
    [6] => <span class="test" style="color:red">
    [7] => consec
    [8] => <i>
    [9] => tet
    [10] => </i>
    [11] => uer
    [12] => </span>
    [13] => .
)

您幾乎可以得到它。 但是,您需要將<[^>]*>更改為更特定的正則表達式<\\/?\\w+[^<>]*>然后需要為空格|\\s+設置替代。 您也不需要i標記:

preg_split('/(<\/?\w+[^<>]*>)|\s+/', $string, null, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE)

暫無
暫無

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

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