Why doesn't PHP's preg_replace function like escaping "\"? - php

I use the RegExr website to test my regular expressions. On that website it can easily find the character "\" with the RegEx string /\\/g. But when I use it in php it throws back:
Warning: preg_replace(): No ending delimiter '/'
My Code
$str = "0123456789 _+-.,!##$%^&*();\/|<>";
echo preg_replace('/\\/', '', $str);
Why doesn't PHP like to escape "\"?

When using it in the regexp use \\ to use it in the replacement, use \\\\ will turn into \\ that will be interpreted as a single backslash.
Use it like this:
<?php
$str = "0123456789 _+-.,!##$%^&*();\/|<>";
echo preg_replace('/\\\\/', '', $str);
Output:
0123456789 _+-.,!##$%^&*();/|<>

Related

Regex Binary Pattern Search in PHP

I am trying to find and replace binary values in strings:
$str = '('.chr(0x00).chr(0x91).')' ;
$str = preg_replace("/\x00\x09/",'-',$str) ;
But I am getting "Warning: preg_replace(): Null byte in regex" error message.
How to work on binary values in Regex/PHP?
It is because you are using double quotes " around your regex pattern, which make the php engine parse the chars \x00 and \x09.
If you use single quotes instead, it will work:
$str = '(' . chr(0x00) . chr(0x91) . ')' ;
$str = preg_replace('/\x00\x09/', '-', $str) ;
But your regex seems also not to be correct, if I understood your question correctly. If you want to replace the chars \x00 and \x91 with a dash -, you must put them into brackets []:
$str = preg_replace('/[\x00\x91]/', '-', $str) ;

PHP: preg_replace() on NameSpace

I'm trying to get the parent "elements" name as string from a PHP namespace in a string, the ideia is to do:
Input: \Base\Util\Review; Desired Output: \Base\Util;
My main problem here is how can I deal with the backslash escaping in the regex expression, so far I can make it work with the normal slash:
$ns = "/Base/Util/Review";
print preg_replace("#\/[^/]*$#", '', $ns);
// Outputs => /Base/Util
Thank you.
This should work:
$s = '\\Base\\Util\\Review';
$r = preg_replace('~\\\\[^\\\\]*$~', '', $s);
//=> \Base\Util
You can do it without preg_replace
$ns = "\Base\Util\Review";
print implode('\\', array_slice(explode('\\',$ns),0,-1));
Another option:
$ns = "\Base\Util\Review";
print substr($ns,0,strrpos($ns,'\\'));
Try this
print preg_replace("#\\\[^\\\]*$#", '', $ns)
You will have to write four backslashes for each literal backslash:
$regex = '#\\\\#'; // regex matching one backslash
You need to escape each \ once to escape its special meaning in the regex, and again escape each \ once to escape its meaning in the PHP string literal.

Remove backslash \ from string using preg replace of php

I want to remove the backslash alone using php preg replace.
For example: I have a string looks like
$var = "This is the for \testing and i want to add the # and remove \slash alone from the given string";
How to remove the \ alone from the corresponding string using php preg_replace
why would you use preg_replace when str_replace is much easier.
$str = str_replace('\\', '', $str);
To use backslash in replacement, it must be doubled (\\\\ PHP string) in preg_replace
echo preg_replace('/\\\\/', '', $var);
You can also use stripslashes() like,
<?php echo stripslashes($var); ?>
$str = preg_replace('/\\\\(.?)/', '$1', $str);
This worked for me!!
preg_replace("/\//", "", $input_lines);

PHP Regex replace tags

I have a piece of text that contains:
[shipping_address]
<p><b>#shipping_title#</b></p>
<p>#shipping_name#<br>
#shipping_streetNrBox#<br>
#shipping_zipcode# #shipping_city#<br>
#shipping_country#<br>
</p>
[/shipping_address]
In php if a certain if statements return true, I want to remove the entire block (including [shipping_address][/shipping_address]). I am using a preg_replace but I need some help with the code.
$content = preg_replace("\[shipping_address\](.*?)\[/shipping_address\]", "" , $content);
does not do the trick, can someone help me out please.
This will do the stuff:
$sData = preg_replace('/\[shipping_address\](.*?)\[\/shipping_address\]/si', '', $sData);
-be aware about using pattern delimiters and multiline replacement (s modifier - in this case, it refers to . (dot) symbol). I've also added i modifier to make replacement case-insensitive.
You should use Pattern Modifiers.
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.
<?php
$string = '123 [shipping_address]
<p><b>#shipping_title#</b></p>
<p>#shipping_name#<br>
#shipping_streetNrBox#<br>
#shipping_zipcode# #shipping_city#<br>
#shipping_country#<br>
</p>
[/shipping_address] test';
var_dump( preg_replace('/\[shipping_address\].*\[\/shipping_address\]/s', '', $string ));
You can try this
preg_replace('/([shipping_address[^>]*])(.*?)([\/shipping_address])/i', '', $string);
If you want to remove the shippingaddress too: then try this
preg_replace('/[shipping_address[^>]*].*?[\/shipping_address]/i', '', $string);
It should work for you:
$content = preg_replace("/\[shipping_address\](.*[\n\r].*)*\[/shipping_address\]/", "" , $content);
You can try this:
$search = "/\[shipping_address\](.*?)\[\/shipping_address]/s";
$replace = " ";
$string = "[shipping_address]
<p><b>#shipping_title#</b></p>
<p>#shipping_name#<br>
#shipping_streetNrBox#<br>
#shipping_zipcode# #shipping_city#<br>
#shipping_country#<br>
</p>
[/shipping_address]";
echo preg_replace($search,$replace,$string);

I have to match php variable in php file

I have to match php variable in the php file using preg_match()
$GLOBALS['app_list_strings']['enjay_host_list'] = array (
How can I do this.
I am doing,
<?php
$filename='/var/www/su/custom/include/language/en_us.lang.php';
$fileopen=file($filename);
//echo $fileopen[2];
$NoOflines = count($fileopen);
echo $NoOflines ."<br>";
$Changed=0;
$Foundon=0;
$FoundFirstClose=0;
for($i=0;$i<$NoOflines;$i++)
{
echo $fileopen[$i]."<br>";
if(preg_match("/\$GLOBALS['app_list_strings']['enjay_host_list']=array ( /i", $fileopen[$i]))
{
$Foundon=$i;
echo $fileopen[$i]."<br>";
}
}
?>
You need to escape every character that has a special meaning in a regexp, which means not only the $ but also [, ] and (. See the PCRE documentation for the list of special characters in pcre regexp.
Another issue is that because you use double quotes, php tries to replace $GLOBALS.. with a variable content unless you double backslash it on top of it, so it's better to just use the Nowdoc syntax (if you use php >= 5.3, which you really should).
$pattern = <<<'EOS'
/\$GLOBALS\['app_list_strings'\]\['enjay_host_list'\]=array \( /i
EOS;
for($i=0;$i<$NoOflines;$i++)
{
echo $fileopen[$i]."<br>";
if(preg_match($pattern, $fileopen[$i]))
{
$Foundon=$i;
echo $fileopen[$i]."<br>";
}
}
your missing some escape characters in your regular expression.
"/\$GLOBALS\['app_list_strings'\]\['enjay_host_list'\]=array\s\(/i"
$string = "\$GLOBALS['app_list_strings']['enjay_host_list']=array (" ;
$match = preg_match("/\\\$GLOBALS\['app\_list\_strings'\]\['enjay\_host\_list'\]\s*=\s*array\s*\(/i", $string);
var_dump($match) ;
Possible issues with your regexp:
You have to escape special chars as ([]_$)
You have to double escape $ sign when using double quotes in PHP
Whitespaces are also important. I used \s* which correspons to 0 or more whitespaces.

Categories