簡體   English   中英

PHP:preg_split

[英]PHP: preg_split

我在這里需要有關正則表達式的幫助。

我希望PHP能夠在數組的各個部分中拆分字符串,以使<%me%>包圍的子字符串將位於其自己的插槽中。

例如

Hi there how are <%me date(); %> => {"Hi there how are ", "<%me date(); %>} 
Hi there how are you<%me date(); %> => {"Hi there how are you", "<%me date(); %>}
Hi there how are you<%me date(); %>goood => {"Hi there how are you", "<%me date(); %>, "good"
Hi there how are you<%me date(); %> good => {"Hi there how are you", "<%me date(); %>}, " good"}

請注意,空白不會阻止標簽的解析。

關於在PREG捕獲分割定界符

您可以使用PREG_SPLIT_DELIM_CAPTURE分割並捕獲定界符。

請記住將分隔符放在捕獲組(…) ,以使其正常工作。

這是一個例子:

$text = 'abc123xyz456pqr';

$parts = preg_split('/(\d+)/', $text, -1, PREG_SPLIT_DELIM_CAPTURE);

print_r($parts);

打印結果( 如ideone.com所示 ):

Array
(
    [0] => abc
    [1] => 123
    [2] => xyz
    [3] => 456
    [4] => pqr
)

參考


回到問題

在這種情況下,您可以嘗試使用定界符模式(<%me[^%]+%>) 那是:

  • <%me ,字面上
  • [^%]+ ,即%
  • %> ,字面上
  • 第一組中捕獲的全部內容

如果%可以出現在標記中,則可以嘗試類似(<%me.*?%>)

這是一個例子:

$text = 'prefix<%me date() %>suffix';

$parts = preg_split('/(<%me[^%]+%>)/', $text, -1, PREG_SPLIT_DELIM_CAPTURE);

print_r($parts);

上面的照片( 如ideone.com所示 ):

Array
(
    [0] => prefix
    [1] => <%me date() %>
    [2] => suffix
)

相關問題

暫無
暫無

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

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