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

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

问题描述

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

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天全站免登陆