PHP Regex replace tags - php

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);

Related

PHP rtrim all trailing special characters

I'm making a function that that detect and remove all trailing special characters from string. It can convert strings like :
"hello-world"
"hello-world/"
"hello-world--"
"hello-world/%--+..."
into "hello-world".
anyone knows the trick without writing a lot of codes?
Just for fun
[^a-z\s]+
Regex demo
Explanation:
[^x]: One character that is not x sample
\s: "whitespace character": space, tab, newline, carriage return, vertical tab sample
+: One or more sample
PHP:
$re = "/[^a-z\\s]+/i";
$str = "Hello world\nhello world/\nhello world--\nhellow world/%--+...";
$subst = "";
$result = preg_replace($re, $subst, $str);
try this
$string = preg_replace('/[^A-Za-z0-9\-]/', '', $string); // Removes special chars.
or escape apostraphe from string
preg_replace('/[^A-Za-z0-9\-\']/', '', $string); // escape apostraphe
You could use a regex like this, depending on your definition of "special characters":
function clean_string($input) {
return preg_replace('/\W+$/', '', $input);
}
It replaces any characters that are not a word character (\W) at the end of the string $ with nothing. \W will match [^a-zA-Z0-9_], so anything that is not a letter, digit, or underscore will get replaced. To specify which characters are special chars, use a regex like this, where you put all your special chars within the [] brackets:
function clean_string($input) {
return preg_replace('/[\/%.+-]+$/', '', $input);
}
This one is what you are looking for. :
([^\n\w\d \"]*)$
It removes anything that is not from the alphabet, a number, a space and a new line.
Just call it like this :
preg_replace('/([^\n\w\s]*)$/', '', $string);

Find last word of a string that has special characters

I am trying to add a span tag to the last word of a string. It works if the string has no special characters. I can't figure out the correct regex for it.
$string = "Onun Mesajı";
echo preg_replace("~\W\w+\s*\S?$~", ' <span>' . '\\0' . '</span>', $string);
Here is the Turkish character set : ÇŞĞÜÖİçşğüöı
You need to use /u modifier to allow processing Unicode characters in the pattern and input string.
preg_replace('~\w+\s*$~u', '<span>$0</span>', $string);
^
Full PHP demo:
$string = "Onun Mesajı";
echo preg_replace("~\w+\s*$~u", '<span>$0</span>', $string);
Also, the regex you need is just \w+\s*$:
\w+ - 1 or more alphanumerics
\s* - 0 or more whitespace (trailing)
$ - end of string
Since I removed the \W from the regex, there is no need to "hardcode" the leading space in the replacement string (removed, too).
You should use the u modifier for regular expressions to set the engine into unicode mode:
<?php
$subject = "Onun äöüß Mesajı";
$pattern = '/\w+\s*?$/u';
echo preg_replace($pattern, '<span>\\0</span>', $subject);
The output is:
Onun äöüß <span>Mesajı</span>
This regex will do the trick for you, and is a lot shorter then the other solutions:
[ ](.*?$)
Here is an example of it:
$string = "Onun Mes*ÇŞĞÜÖİçşğüöıajı";
echo preg_replace('~[ ](.*?$)~', ' <span>' .'${1}'. '</span>', $string);
Will echo out:
Onun <span>Mes*ÇŞĞÜÖİçşğüöıajı</span>
The way this regex works is that we look for any characters without space in lazy mode [ ].*?.
then we add the $ identifier, so it matches from the end of the string instead.

How to remove leading characters and the query character with a regular expression in PHP?

I am using preg_replace() and a regular expression to remove all characters before a hyphen (-). I'd like to update the expression to also remove the hyphen itself. The full line of code is shown below in context.
$item['options']['Size'] = preg_replace('/^[^-]*/', '', $item['options']['Size']);
So as it stands let's say I have the below string:
TEST123-150X200
The current preg_replace function will leave me with:
-150X200
I'd like to end up with:
150X200
Could anyone suggest how I can update the regular_expression to achieve this. Thanks
You can add a hyphen at the end of the pattern.
$item['options']['Size'] = preg_replace('/^[^-]*-/', '', $item['options']['Size']);
^
This way, the hyphen is matched (=consumed) and will be removed. Note that [^-] is a negated character class that matches any character but a -. Thus the hyphen was not matched by your original regex.
A non-regex approach:
$item['options']['Size'] = ltrim(strstr($item['options']['Size'], '-'),'-');
See IDEONE demo
<?php
$item = 'TEST123-150X200'; // string here
echo preg_replace('/^[^-]*-/', '', $item);
?>
In addition to the answers/comments given, you could also use a positive lookbehind and replace this:
<?php
$str = "TEST123-150X200";
$regex = '/.*(?<=-)/i';
$item['options']['Size'] = preg_replace($regex, '', $str);
// output: 150X200
?>
Alternatively (as described in the comment), start counting from 1:
$item['options']['Size'] = substr(preg_replace('/^[^-]*/', '', $item['options']['Size']), 1);
I dont think it needs a regex for this...
$str = "TEST123-150X200";
var_dump(end(explode("-", $str))); //string(7) "150X200"
var_dump(ltrim(strstr($str, "-"), "-"));//string(7) "150X200"
var_dump(substr(strrchr($str, "-"), 1) );//string(7) "150X200"

how to remove everything before second occurance of underscore

I couldn't find the solution using search.
I am looking for a php solution to remove all character BEFORE the second occurance of and underscore (including the underscore)
For example:
this_is_a_test
Should output as:
a_test
I currently have this code but it will remove everything after the first occurance:
preg_replace('/^[^_]*.s*/', '$1', 'this_is_a_test');
Using a slightly different approach,
$s='this_is_a_test';
echo implode('_', array_slice( explode( '_', $s ),2 ) );
/* outputs */
a_test
preg_replace('/^.*_.*_(.*)$/U', '$1', 'this_is_a_test');
Note the U modifier which tells regex to take as less characters for .* as possible.
You can also use explode, implode along with array_splice like as
$str = "this_is_a_test";
echo implode('_',array_splice(explode('_',$str),2));//a_test
Demo
Why go the complicated way? This is a suggestion though using strrpos and substr:
<?php
$str = "this_is_a_test";
$str_pos = strrpos($str, "_");
echo substr($str, $str_pos-1);
?>
Try this one.
<?php
$string = 'this_is_a_test';
$explode = explode('_', $string, 3);
echo $explode[2];
?>
Demo
I'm still in favor of a regular expression in this case:
preg_replace('/^.*?_.*?_/', '', 'this_is_a_test');
Or (which looks more complex here but is easily adjustable to N..M underscores):
preg_replace('/^(?:.*?_){2}/', '', 'this_is_a_test');
The use of the question mark in .*? makes the match non-greedy; and the pattern has been expanded from the original post to "match up through" the second underscore.
Since the goal is to remove text the matched portion is simply replaced with an empty string - there is no need for a capture group or to use such as the replacement value.
If the input doesn't include two underscores then nothing is removed; such can be adjusted, very easily with the second regular expression, if the rules are further clarified.

str_replace spaces with hyphens in A tag's name attribute

$string = preg_replace("#[name=([a-zA-Z0-9 .-]+)*]#",''."$1",$string);
This part of script doesn't work:
str_replace(' ', '-', "$1")
I need to replace " " with "-",
i also try preg_replace inside main preg_replace, str_ireplace also
But this is still don't working
The replacement is evaluated upfront and not on each replace. But you can do so by either using the e modifier in your regular expression:
$string = preg_replace("#\[name=([a-zA-Z0-9 .-]+)*]#e", '"<td>$1</td>"', $string);
Or by using preg_replace_callback:
function callbackFunction($match) {
global $front_page;
return '<td>'.$match[1].'</td>';
}
$string = preg_replace_callback("#\[name=([a-zA-Z0-9 .-]+)*]#", 'callbackFunction', $string);
I guess you will have to do it in two steps, since $1 cannot be used in str_replace(). $1 doesn’t really exist as a variable, it is only a placeholder in the replacement string.

Categories