1

我要执行正则表达式的内容是这样的:

[NON-CA]
This is for Non CA
<b> In a New Line </b> 
[/NON-CA]
[CA]
This is for CA
[/CA]

我想根据加拿大的国家代码删除内容,所以如果用户来自加拿大CA,他只能看到部分内容,而对其他人来说只有NON-CA部分可见。标签之间的内容可以是任何换行符、空格、特殊字符、HTML 标记、HTML 实体。这是我写的代码:

<?php
    $content = "[NON-CA]This is for Non CA<b> In a New Line </b> [/NON-CA]    [CA]This is for CA[/CA]";
    $CApattern = "~\[CA\](.*?)\[/CA\]~";
    $NonCApattern = "~\[NON-CA\](.*?)\[/NON-CA\]~";                       
    $NonCApatternsReplacement = array();
    $Replacepatterns = array();        
    $Replacepatterns[] = "~\[CA\]~";
    $Replacepatterns[] = "~\[/CA\]~";
    $NonCApatternsReplacement[] = "~\[NON-CA\]~";
    $NonCApatternsReplacement[] = "~\[/NON-CA\]~"; 

    if($country_code ==  "CA"){ //if its the user of country Canada remove the NON-CA Tag                                
        $result_p1 = preg_replace($NonCApattern, "", $content, -1, $count);                                                                                                                                
        $result_p2 = preg_replace($Replacepatterns, "", $result_p1, -1);
     }
     else{ //if user is not from CANADA remove CA tag and Text                                     

        $result_p1 = preg_replace($NonCApatternsReplacement, "", $content, -1);                                                             
        $result_p2 = preg_replace($CApattern,"", $result_p1, -1, $count);                                                                                                                     
     } 
     echo $result_p2
?>

因此,如果加拿大用户来了,它会生成如下内容:

[NON-CA]
This is for Non CA
<b> In a New Line </b> 
[/NON-CA]
This is for CA

实际上应该是这样的:

This is for CA

如果非加拿大用户到达,则生成的文本如下:

This is for Non CA
<b> In a New Line </b>     
[CA]
This is for CA
[/CA]

实际上应该是这样的:

This is for Non CA
<b> In a New Line </b>   

它不会根据条件替换/删除不应对相应用户可见的内容部分。我的正则表达式有问题吗?

4

2 回答 2

4

您忘记了s 修饰符,您还将使用 dot 匹配换行符.

 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. 

我虽然提供了一个更短的代码:

$string = '[NON-CA]
This is for Non CA
<b> In a New Line </b> 
[/NON-CA]
[CA]
This is for CA
[/CA]';

$remove = 'NON-CA';
$result = preg_replace('/\['.$remove.'\].*?\[\/'.$remove.'\]/s', '', $string);
echo $result;

在线演示

于 2013-05-01T07:49:00.643 回答
2

您可以一次性完成所有这些操作:

$country_code = 'CA'; // for example

$content = <<<LOD
[NON-CA]This is for Non CA<b> In a New Line </b> [/NON-CA]
[CA]This is for CA[/CA]
LOD;

$kr = array('CA', 'NON-CA'); // switch keep/remove
if ($country_code == 'CA') $kr = array_reverse($kr); 

$pattern = '~\[(?:' . $kr[0] . '][^[]++\[/' . $kr[0] . ']|/?' . $kr[1] . '])~';

$result = preg_replace($pattern, '', $content);
于 2013-05-01T08:31:53.373 回答