Php 使用regexp挑选文本
我有 并希望使用preg_替换完成Php 使用regexp挑选文本,php,regex,preg-replace,Php,Regex,Preg Replace,我有 并希望使用preg_替换完成 $text='remove1 \solution{keep1} remove2 \solution{keep2 inner{text}} remove3'; 我几乎有了一个使用 \solution{keep1}\solution{keep2 inner{text}} 但这并不能将\解决方案放在前面。我怎样才能解决这个问题 编辑:\solution是要搜索的固定字符串,所有其他文本段都是任意的。捕获所需的文本,然后内爆 $re = '/[^{}]*+(\{
$text='remove1 \solution{keep1} remove2 \solution{keep2 inner{text}} remove3';
我几乎有了一个使用
\solution{keep1}\solution{keep2 inner{text}}
但这并不能将\解决方案放在前面。我怎样才能解决这个问题
编辑:\solution是要搜索的固定字符串,所有其他文本段都是任意的。捕获所需的文本,然后内爆
$re = '/[^{}]*+(\{(?:[^{}]++|(?1))*\})[^{}]*+/';
$text = preg_replace($re, '$1', $text);
- 我认为应该删除
等,因为它们有空格将它们与其他字符串组件分隔开?我看不到任何其他规则来消除它们。因此,您的字符类应该是remove1
[^{}\s]
- 此外,尽管它不会破坏正则表达式引擎,
和[^{}]*+
将极大地降低它的速度,而不会产生任何影响。只需使用[^{}]+
或[^{}]*
[^{}]+
preg_match_all('#\solution\{[^\}]*\}#msi', $text, $matches);
$text = implode($matches[0],'');
输出
$text = 'remove1 \solution{keep1} remove2 \solution{keep2 inner{text}} remove3';
$re = '/ \\\\solution ( \{ [^{}]* (?: (?1) [^{}]* )* \} ) [^{}\s]* /x';
preg_match_all($re, $text, $matches);
$text = join($matches[0]);
echo $text;
\solution{keep1}\solution{keep2 internal{text}},上面的第二个代码行。我可以假设您想要的字符串总是以
\solution{
开头吗?嵌套的大括号对之后是否会有文本,比如\solution{keep2 internal text}keep3}
?我想应用到一个latex文档,搜索\solution some{some text}然后收集所有这些表达式。哦,回答你的评论,是的。可能的重复,我没有得到任何输出。但可能我测试了你的想法。我有一个三行的测试文件:$text=…;
然后是你的两行,同时回显最后一行。我认为需要转义\solution的反斜杠,但所有如果我做preg\u match\u all(“#solution\{[^\}]*\}msi',$text,$matches),也是一样的代码>然后我得到输出:solution{keep1}solution{keep2 internal{text}
。注意最后一个}丢失了。@Aram OP最初使用递归的技术是保留嵌套大括号所必需的。这是可行的,但是\solution在regexp中的什么位置?它怎么知道只找这个?还是我遗漏了什么?比如说,我现在想使用这种技术来收集\question,然后我会怎么做?我意识到你的代码没有工作,因为它收集了所有\something{text},而我只想要\solution{something}。很难从你的问题中准确地说出你想要什么。原来remove
可以是任何文本,而solution
是字面意思。在您自己的正则表达式中没有提到\solution
,所以我假设它是在一个大括号之前的任何非空格序列。我已经修改了我的答案以满足您的要求。自从您现在说\solution{keep2 internal{text}keep3}
应该匹配后,我再次修改了我的答案。为什么要使用四个反斜杠。我明白这是逃跑的原因,但为什么是四次?
\solution{keep1}\solution{keep2 inner{text}}