dongqing904999 2011-11-28 22:02
浏览 26
已采纳

检测字符串中的括号模式

Detecting a parenthesis pattern in a string

This is a line (an example between parenthesis).

or

This is a line(an example between parenthesis).

I need to separate both strings in:

$text = 'This is a line.';

$eg = 'an example between parenthesis';

I have this code so far:

$text = 'This is a line (an example between parenthesis)';
preg_match('/\((.*?)\)/', $text, $match);
print $match[1];

But it only brings the text inside the parenthesis. I also need the text outside the parenthesis.

  • 写回答

4条回答 默认 最新

  • donglu6303 2011-11-28 22:06
    关注
    $text = 'This is a line (an example between parenthesis)';
    preg_match('/(.*)\((.*?)\)(.*)/', $text, $match);
    echo "in parenthesis: " . $match[2] . "
    ";
    echo "before and after: " . $match[1] . $match[3] . "
    ";
    

    UPDATE after clarification of question .. now with many parenthesis:

    $text = "This is a text (is it?) that contains multiple (example) stuff or (pointless) comments in parenthesis.";
    $remainder = preg_replace_callback(
            '/ {0,1}\((.*)\)/U',
            create_function(
                '$match',
                'global $parenthesis; $parenthesis[] = $match[1];'
            ), $text);
    echo "remainder text: " . $remainder . "
    ";
    echo "parenthesis content: " . print_r($parenthesis,1) . "
    ";
    

    results in:

    remainder text: This is a text that contains multiple stuff or comments in parenthesis.
    parenthesis content: Array
    (
        [0] => is it?
        [1] => example
        [2] => pointless
    )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 对于这个问题的代码运行
  • ¥50 三种调度算法报错 有实例
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败