php 字符串截取 preg_relpace array,php – 使用preg_replace截断字符串的最有效方法?...

我正在查看一些代码并开始考虑使用preg_replace截断字符串(在本例中为URI)的最有效方法.

首先 – 我意识到首先使用preg_replace对于这个任务来说可能是过度的,它可能是不必要的昂贵,并且最好使用PHP的字符串友好函数(如substr)来处理它.我知道这个.

也就是说,考虑这两种不同的正则表达式:

$uri = '/one/cool/uri'; // Desired result '/one/cool'

// Using a back-reference

$parent = preg_replace('#(.*)/.*#', "$1", $uri);

// Using character class negation

$parent = preg_replace('#/[^/]+$#', '', $uri);

默认情况下,我认为在前一种情况下,创建后向引用将比不这样做更昂贵,因此第二个示例将更可取.但后来我开始想知道在第二个例子中使用[^ /]是否比相应的更昂贵.在第一个例子中,如果是这样,还有多少?

从可读性的角度来看,我更喜欢第一个例子,因为我们分裂了头发,所以我倾向于在两者之间选择它(毕竟,编写可读代码也很有价值).可能只是我个人的偏好.

思考?

最佳答案 我也会测量两种选择的运行时间.来自文档的这些信息也可能有所帮助:

If you are using such a pattern with subject strings that do not contain newlines, the best performance is obtained by setting PCRE_DOTALL, or starting the pattern with ^.* to indicate explicit anchoring. That saves PCRE from having to scan along the subject looking for a newline to restart at.

所以,$parent = preg_replace(‘#^(.*)/.*#s’,“$1”,$uri);可能会加速第一种选择.第二个不需要这个设置:

s (PCRE_DOTALL)

If this modifier is set, a dot metacharacter in the

pattern matches all characters, including newlines. Without it,

newlines are excluded. This modifier is equivalent to Perl’s /s

modifier. A negative class such as [^a] always matches a newline

character, independent of the setting of this modifier.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值