PHP:提取括号内文本的最佳方法? [英] PHP: Best way to extract text within parenthesis?

查看:44
本文介绍了PHP:提取括号内文本的最佳方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在括号之间提取文本集的最佳/最有效方法是什么?假设我想以最有效的方式从字符串忽略除此(文本)之外的所有内容"中获取字符串文本".

What's the best/most efficient way to extract text set between parenthesis? Say I wanted to get the string "text" from the string "ignore everything except this (text)" in the most efficient manner possible.

到目前为止,我想出的最好的是:

So far, the best I've come up with is this:

$fullString = "ignore everything except this (text)";
$start = strpos('(', $fullString);
$end = strlen($fullString) - strpos(')', $fullString);

$shortString = substr($fullString, $start, $end);

有没有更好的方法来做到这一点?我知道一般使用正则表达式效率较低,但除非我可以减少函数调用的次数,否则这可能是最好的方法?想法?

Is there a better way to do this? I know in general using regex tends to be less efficient, but unless I can reduce the number of function calls, perhaps this would be the best approach? Thoughts?

推荐答案

我只想做一个正则表达式并解决它.除非您进行了足够多的迭代,否则它会成为一个巨大的性能问题,否则编码会更容易(并在您回顾时理解)

i'd just do a regex and get it over with. unless you are doing enough iterations that it becomes a huge performance issue, it's just easier to code (and understand when you look back on it)

$text = 'ignore everything except this (text)';
preg_match('#((.*?))#', $text, $match);
print $match[1];

这篇关于PHP:提取括号内文本的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆