preg_replace()模式可删除php中的括号和内容 [英] preg_replace() pattern to remove brackets and content in php

查看:80
本文介绍了preg_replace()模式可删除php中的括号和内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用preg_replace()删除包含其内容的方括号,但是由于结尾方括号是结束字符,因此我无法在模式中使用惰性(非贪心),方括号之间的文本始终是随机字符长度,可以包含数字,下划线和连字符。

I want to remove the brackets with its content using preg_replace(), but i am unable to use a lazy(non-greedy) in the pattern since the end bracket is the end character, the text in between the brackets is always a random character length and can contain numbers, underscores, and hyphens.

code-

$array = array(
   "Text i want to keep (txt to remove)",
   "Random txt (some more random txt)",
   "Keep this (remove)",
   "I like bananas  (txt)"
);

$pattern = "@pattern@";
foreach($array as $new_txt){
   $new_outputs .= preg_replace($pattern, '', $new_txt)."\n";
}
echo $new_outputs;

想要的输出-

Text i want to keep
Random txt
Keep this
I like bananas

我不使用正则表达式,也找不到解决我问题的方法。

I do not use regular expressions much and couldn't find anything to solve my problem.

推荐答案

应该使用以下正则表达式:

The following regular expression should do it:

$pattern = '@\(.*?\)@';

。*?是非贪婪的任何东西都匹配。

.*? is a non-greedy match of anything.

这篇关于preg_replace()模式可删除php中的括号和内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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