2014-07-18 62 views
1

兩個字符之間的字符串我在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正則表達式? 感謝您的閱讀:)

回答

0

一個更緊湊的版本:

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

看到比賽中the regex demo

匹配

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

說明

  • ^錨斷言,我們是在字符串
  • <#開頭的左定界符
  • 的匹配告訴發動機放棄迄今爲止與最終比賽匹配的東西,它返回
  • .*?懶洋洋地匹配chars直到點...
  • 先行(?=#>)可以斷言,接下來是#>
  • $錨斷言,我們是在字符串

結束參考

+0

供參考:增加了解釋,演示和參考。 :) – zx81

+0

感謝您的快速回復! 幫助:) – mmt

+0

非常歡迎,很高興幫助! :) – zx81

0

你可以使用這個表達式:

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

preg_match_all函數調用。

我不想給你完整的代碼,但這應該足以讓你去。

1

此代碼將做你想做的

<?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]); 
0

通過前瞻和回顧後,

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

最後調用函數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" 
    } 
}