簡體   English   中英

在PHP中獲取兩個字符之間的字符串

[英]Get string between two characters in php

我在php中有一個字符串說

$string = 'All I want to say is that <#they dont really care#> about us.
    I am wasted away <#I made a million mistake#>, am I too late. 
    Theres a storm in my head and a race on my bed, <#when you are not near#>' ;


$expected_output = array(
    'they dont really care',
    'I made a million mistake',
    'when you are not near'
);

我如何使用PHP regex實現這一點? 謝謝閱讀 :)

該代碼將完成您想要的

<?php

$string = 'All I want to say is that <#they dont really care#> about us.
    I am wasted away <#I made a million mistake#>, am I too late. 
    Theres a storm in my head and a race on my bed, <#when you are not near#>' ;


preg_match_all('/<#(.*)#>/isU', $string, $matches);

var_dump($matches[1]);

您可以使用此正則表達式:

'/<#(.*?)#>/s'

preg_match_all函數調用中。

我不想給您完整的代碼,但這應該足以讓您繼續前進。

通過向前和向后看,

(?<=<#).*?(?=#>)

最后,調用preg_match_all函數以打印匹配的字符串。

您的PHP代碼

<?php
$data = 'All I want to say is that <#they dont really care#> about us.
    I am wasted away <#I made a million mistake#>, am I too late. 
    Theres a storm in my head and a race on my bed, <#when you are not near#>' ;
$regex =  '~(?<=<#).*?(?=#>)~';
preg_match_all($regex, $data, $matches);
var_dump($matches);
?>

輸出:

array(1) {
  [0]=>
  array(3) {
    [0]=>
    string(21) "they dont really care"
    [1]=>
    string(24) "I made a million mistake"
    [2]=>
    string(21) "when you are not near"
  }
}

更緊湊的版本:

$regex = '~<#\K.*?(?=#>)~';
preg_match_all($regex, $string, $matches);
print_r($matches[0]);

正則表達式演示中查看匹配項。

火柴

they dont really care
I made a million mistake
when you are not near

說明

  • ^錨斷言我們在字符串的開頭
  • <#匹配左定界符
  • \\K告訴引擎放棄與最終匹配相距甚遠的匹配,它返回
  • .*? 懶惰地匹配字符,直到...
  • 先行(?=#>)可以斷言以下是#>
  • $錨斷言我們在字符串的末尾

參考

暫無
暫無

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

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