开发者

PHP: regex & hash key in string

开发者 https://www.devze.com 2023-01-16 20:57 出处:网络
How do I address special characters in Regex? @ ? # $ % %...开发者_运维百科 this patten searches for a letter that comes between a prefix and a suffix.

How do I address special characters in Regex? @ ? # $ % %...开发者_运维百科

this patten searches for a letter that comes between a prefix and a suffix.

$pattern = '/((?<!\b$PREFIX)$LETTER|$LETTER(?!$SUFFIX\b))/i';

$string = 'end'; 

$prefix = 'e';  
$letter = 'n';  
$suffix = 'd';  

But what if $string began with a #

$string = '#end';
$prefix = ???

edit: This is the preg_replace in full

$text = "<p>Newton, Einsteing and Edison. #end</p>"
$pattern = '/((?<!\b$PREFIX)$LETTER|$LETTER(?!$SUFFIX\b))/i';
echo preg_replace($pattern, '<b>\1</b>', $text);

this replaces all the n letters with a bold n but is supposed to exculde the n in #end


You have to enclose your pattern with double quote to make the variables interpolated.

$pattern = "/((?<!\b$PREFIX)$LETTER|$LETTER(?!$SUFFIX\b))/i";

And more, you define $prefix (lower case) and use $PREFIX (uppercase). So the script becomes the following and works fine for me :

<?php
$PREFIX = 'e';  
$LETTER = 'n';  
$SUFFIX = 'd';  
$text = "<p>Newton, Einsteing and Edison. #end</p>";
$pattern = "/((?<!\b$PREFIX)$LETTER|$LETTER(?!$SUFFIX\b))/i";
echo preg_replace($pattern, "<b>$1</b>", $text),"\n";
?>

Output:

<p><b>N</b>ewto<b>n</b>, Ei<b>n</b>stei<b>n</b>g a<b>n</b>d Ediso<b>n</b>. #end</p>

without code formating:

Newton, Einsteing and Edison. #end


You have to escape the special chars first with a backslash. But as the backslash already escape letters in a string, you'll have to escape your backslash first.

$string = '\\#end';

A better way to do this is to use the preg_quote() function on your string, and specify what kind of delimiter you use (here "/").

preg_quote($string, '/');
0

精彩评论

暂无评论...
验证码 换一张
取 消