【问题标题】:Separate string within bracket where number of bracket varies括号内的单独字符串,括号数不同
【发布时间】:2013-02-09 12:27:25
【问题描述】:

这是我在这里的第一个问题,我搞砸了字符串。我有一些格式如下的字符串:

     I will be here (I may or may not be here) (30-Apr-2013) 
     I am still here (15-Feb-2013)
     I am still here(I may not be here) (I may not be here) (9-Apr-2013) 

我需要将日期与名称分开。如您所见,括号的数量可能会有所不同,但我只需要最后一个(字符串的其余部分将被视为名称)。

预期输出:

1. array( 0=> 'I will be here (I may or may not be here)' , 1=> '30-Apr-2013' )
2. array( 0=> 'I am still here' , 1=> '15-Feb-2013' )
3. array( 0=> ' I am still here(I may not be here) (I may not be here)' , 1=> '9-Apr-2013' )

实现这一目标的最佳方法是什么?

【问题讨论】:

  • @negvoters 想解释一下这个问题有什么问题?

标签: php string pattern-matching


【解决方案1】:

您可以使用strrpos 查找最后一次出现的(,然后您可以使用substrtrim 获取子字符串并将它们修剪成您想要的结果。


例如

/**
 * Return an array with the "name" as the first element and
 * date as the second.
 */
function fun($string)
{
    $datePos = strrpos($string, '(');
    return array (
        trim(substr($string, 0, $datePos - 1)), trim(substr($string, $datePos), ' ()')
    );
}

【讨论】:

  • @czarpino 谢谢,我以为我会让 OP 这样做 :-) 顺便说一句,我在 trim 添加了一个字符列表,因为这就是我提到它的原因...
  • 啊,是的,多么尴尬。我才意识到。
  • 像魅力一样工作!非常感谢@jeroen :-)
猜你喜欢
  • 2015-12-14
  • 2016-08-19
  • 1970-01-01
  • 1970-01-01
  • 2022-11-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多