2013-04-30 25 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));