在php中获取两个字符之间的字符串

时间:2014-07-18 09:59:21

标签: php regex preg-match preg-match-all pcre

我在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正则表达式实现此目的? 感谢您阅读:)

4 个答案:

答案 0 :(得分: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]);

答案 1 :(得分:0)

您可以使用此正则表达式:

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

preg_match_all函数调用中。

我不想给你完整的代码,但这应该足以让你前进。

答案 2 :(得分: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"
  }
}

答案 3 :(得分: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

<强>解释

  • ^锚点断言我们位于字符串的开头
  • <#匹配左分隔符
  • \K告诉引擎放弃与其返回的最终匹配项目匹配的内容
  • .*?懒洋洋地将字符匹配到......
  • 前瞻(?=#>)可以断言后面的内容是#>
  • $锚点断言我们位于字符串的末尾

<强>参考