[英]Get string between two characters in php
I have a string in php say 我在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'
);
How can I acheive this using PHP regex ? 我如何使用PHP regex实现这一点? Thanks for reading :) 谢谢阅读 :)
This code will do what you want 该代码将完成您想要的
<?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]);
You can use this regex: 您可以使用此正则表达式:
'/<#(.*?)#>/s'
in preg_match_all
function call. 在preg_match_all
函数调用中。
I don't want to give you full code but this should be good enough to get you going. 我不想给您完整的代码,但这应该足以让您继续前进。
Through lookahead and lookbehind, 通过向前和向后看,
(?<=<#).*?(?=#>)
Finally call preg_match_all
function to print the matched strings. 最后,调用preg_match_all
函数以打印匹配的字符串。
Your PHP code would be, 您的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);
?>
Output: 输出:
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"
}
}
A more compact version: 更紧凑的版本:
$regex = '~<#\K.*?(?=#>)~';
preg_match_all($regex, $string, $matches);
print_r($matches[0]);
See the matches in the regex demo . 在正则表达式演示中查看匹配项。
Matches 火柴
they dont really care
I made a million mistake
when you are not near
Explanation 说明
^
anchor asserts that we are at the beginning of the string ^
锚断言我们在字符串的开头 <#
matches the left delimiter <#
匹配左定界符 \\K
tells the engine to drop what was matched so far from the final match it returns \\K
告诉引擎放弃与最终匹配相距甚远的匹配,它返回 .*?
lazily matches chars up to the point where... 懒惰地匹配字符,直到... (?=#>)
can assert that what follows is #>
先行(?=#>)
可以断言以下是#>
$
anchor asserts that we are at the end of the string $
锚断言我们在字符串的末尾 Reference 参考
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.