2013-04-30 21 views
0

的内容我有一个字符串这样<script>||| [CA]this is my content<br> ABC**&&PPPP[/CA]Just Some Random Text<span>[CA]this is my content2<br> 123**''&&PPPP[/CA]我有这样的/\[CA\](.*)\[\/CA\]/上面的字符串正则表达式我已经尝试了PHP的preg_replace()得到输出文本之外[CA] [/CA]标签应该是这样的:的preg_replace不更换串

<script>||| Just Some Random Text<span>但我这里无法获得所需要的结果是我的全码:

<?php 
     $content = "<script>||| [CA]this is my content<br> ABC**&&PPPP[/CA]Just Some Random Text<span>[CA]this is my content2<br> 123**''&&PPPP[/CA]"; 
     $CApattern = "/\[CA\](.*)\[\/CA\]/"; 
     $content = preg_replace($CApattern,"", $content, -1,$count); 
     echo $content; 
?> 

是有什么问题正则表达式?

+0

你确定你看'echo'ing后的HTML _source_?你意识到那些''标签将阻止你的浏览器显示输出结果?我看不到你还有什么“没有”。 – 2013-04-30 21:37:10

回答

4

只需添加?所以.*勉强懒洋洋地,即尽可能少的时间越好,否则.*将匹配匹配权高达[/CA]字符串中的最后一次出现。

"/\[CA\](.*?)\[\/CA\]/" 

顺便说一句,你并不需要包括-1,作为它的默认值,或$count,如果你不打算使用它。

+0

感谢您的回复,我也尝试过使用'?',但它的效果不佳 – Seeker 2013-04-30 21:21:13

+1

@PHPSeeker。它将与你发布的代码一起工作。请更详细地描述它是如何工作的。 – MikeM 2013-04-30 21:22:50

+1

@MikeM我测试了它[在正则表达式测试网站](http://www.spaweditor.com/scripts/regex/index.php),是的它的工作原理 – reikyoushin 2013-04-30 21:24:17

2

我跑到下面的代码在http://writecodeonline.com

$content = "&lt;script>||| [CA]this is my content<br> ABC**&&PPPP[/CA]Just Some Random Text<span>[CA]this is my content2<br> 123**''&&PPPP[/CA]"; 
$CApattern = "/\[CA\](.*?)\[\/CA\]/"; 
$content = preg_replace($CApattern, "", $content); 
echo $content; 

请注意,我把它换成第一<&lt;。输出:

<script>||| Just Some Random Text 

确保你是不是在找原始输出浏览器—的<script>标签将阻止看到,当然,你的输出。

+0

感谢队友的回答:)它帮助 – Seeker 2013-04-30 21:44:20

+1

我不认为你应该修改内容/输入字符串以从中受益正则表达式..它应该保持原样('<') – reikyoushin 2013-04-30 21:44:26

+1

@reikyoushin - 我有一种感觉,他的问题必须与HTML标记,而不是PHP代码。我不想用复杂的方式解释这一点;我想给他看一个选择,让他自己找出其他的。当然,我的意图不是要改变被正版化的内容。 – 2013-04-30 21:45:38

0

如果你只是想赶上那是内外[CA]标签外,您可以使用preg_match_all:

$subject = "<script>||| [CA]this is my content<br> ABC**&&PPPP[/CA]Just Some Random Text<span>[CA]this is my content2<br> 123**''&&PPPP[/CA]"; 
$pattern = '~(?>\[CA](?<inside>.*?)\[/CA])|(?<outside>[^[]++|\[(?!CA]))~'; 
preg_match_all($pattern, $subject, $matches); 
foreach ($matches as $key=>&$value) { if (is_numeric($key)) unset($matches[$key]); } 
echo htmlspecialchars(print_r($matches, true));