PHP String Pattern Replace - php

I have a set of strings like this:
Pants [+$50]
Shirts [+$10]
Jeans [+$5]
Jackets [+$100]
How can I remove the ' [xxx]' in these lines and leaving just the item name (without the trailing space)? I was told to define a regular expression, not sure how that works...

That's actually a bit of a confusing regex, since [ and ] are special characters:
$str = 'Pants [+$50]';
$str = rtrim(preg_replace('/\[[^\]]*\]/', '', $str));
// 'Pants'
Basically the partern \[[^\]]*\] means to match a literal [ followed by 0 or more characters that are not ] followed by a ]. The second string in preg_replace is what it gets replaced with. In this case the empty string since we want to remove it. Then we use rtrim to trim any trailing whitespace.

Try this one:
The RegEx
(?im)[ \t]*\[[^\]\[]+\][ \t]*$
Code
$result = preg_replace('/^(.+?)[ \t]*\[[^\][]+\][ \t]*$/im', '$1', $subject);

Related

How to replace all occurrences of a character except the first one in PHP using a regular expression?

Given an address stored as a single string with newlines delimiting its components like:
1 Street\nCity\nST\n12345
The goal would be to replace all newline characters except the first one with spaces in order to present it like:
1 Street
City ST 12345
I have tried methods like:
[$street, $rest] = explode("\n", $input, 2);
$output = "$street\n" . preg_replace('/\n+/', ' ', $rest);
I have been trying to achieve the same result using a one liner with a regular expression, but could not figure out how.
I would suggest not solving this with complicated regex but keeping it simple like below. You can split the string with a \n, pop out the first split and implode the rest with a space.
<?php
$input = explode("\n","1 Street\nCity\nST\n12345");
$input = array_shift($input) . PHP_EOL . implode(" ", $input);
echo $input;
Online Demo
You could use a regex trick here by reversing the string, and then replacing every occurrence of \n provided that we can lookahead and find at least one other \n:
$input = "1 Street\nCity\nST\n12345";
$output = strrev(preg_replace("/\n(?=.*\n)/", " ", strrev($input)));
echo $output;
This prints:
1 Street
City ST 12345
You can use a lookbehind pattern to ensure that the matching line is preceded with a newline character. Capture the line but not the trailing newline character and replace it with the same line but with a trailing space:
preg_replace('/(?<=\n)(.*)\n/', '$1 ', $input)
Demo: https://onlinephp.io/c/5bd6d
You can use an alternation pattern that matches either the first two lines or a newline character, capture the first two lines without the trailing newline character, and replace the match with what's captured and a space:
preg_replace('/(^.*\n.*)\n|\n/', '$1 ', $input)
Demo: https://onlinephp.io/c/2fb2f
I leave you another method, the regex is correct as long as the conditions are met, in this way it always works
$string=explode("/","1 Street\nCity\nST\n12345");
$string[0]."<br>";
$string[1]." ".$string[2]." ".$string[3]

Remove empty space and carriage return from a string with ] at end and [ at the start of the next line

I am relatively new to regular expressions. I just wanted to know that how to replace empty spaces or carriage return ( new line ) through preg_replace in php for this string:
[someshortcode]
[someshortcode]
The string has ] at the end of one line and [ at the new line. I want to remove any spaces/ characters be it '\r' ,'\t', '\n', empty spaces or any other character
output should be like this: [someshortcode][someshortcode]
Thanks
$result = preg_replace("/\s/", '', $string);
You can learn more about the "\s" and others in Escape sequences
Update:
I'd like to add an alternative with POSIX compliant regular expression, where you could use the following line, which by the way would also match the VT character (code 11):
$result = preg_replace("/[[:space:]]/", '', $string);
More about Character classes

remove double square brackets and keep the string

I need to remove all square brackets from a string and keep the string. I've been looking around but all topic OP's want to replace the string with something.
So: [[link_to_page]]
should become: link_to_page
I think I should use php regex, can someone assist me?
Thanks in advance
You can simply use a str_replace.
$string = str_replace(array('[[',']]'),'',$string);
But this would get a '[[' without a ']]' closure. And a ']]' without a '[[' opening.
It's not entirely clear what you want - but...
If you simply want to "remove all square brackets" without worrying about pairing/etc then a simple str_replace will do it:
str_replace( array('[',']') , '' , $string )
That is not (and doesn't need to be) a regex.
If you want to unwrap paired double brackets, with unknown contents, then a regex replace is what you want, which uses preg_replace instead.
Since [ and ] are metacharacters in regex, they need to be escaped with a backslash.
To match all instances of double-bracketed text, you can use the pattern \[\[\w+\[\] and to replace those brackets you can put the contents into a capture group (by surrounding with parentheses) and replace all instances like so:
$output = preg_replace( '/\[\[(\w+)\[\]/' , '$1' , $string );
The \w matches any alphanumeric or underscore - if you want to allow more/less characters it can be updated, e.g. \[\[([a-z\-_]+)\[\] or whatever makes sense.
If you want to act on the contents of the square brackets, see the answer by fluminis.
You can use preg_replace:
$repl = preg_replace('/(\[|\]){2}/', '', '[[link_to_page]]');
OR using str_replace:
$repl = str_replace(array('[[', ']]'), '', '[[link_to_page]]');
If you want only one match :
preg_match('/\[\[([^\]]+)\]\]/', $yourText, $matches);
echo $matches[1]; // will echo link_to_page
Or if you want to extract all the link from a text
preg_match_all('/\[\[([^\]]+)\]\]/', $yourText, $matches);
foreach($matches as $link) {
echo $link[1];
}
How to read '/\[\[([^\]]+)\]\]/'
/ start the regex
\[\[ two [ characters but need to escape them because [ is a meta caracter
([^\]]+) get all chars that are not a ]
\]\] two ] characters but need to escape them because ] is a meta caracter
/ end the regex
Try
preg_replace(/(\[\[)|(\]\])/, '', $string);

How to trim special chars from string?

I want to remove all non-alphanumeric signs from left and right of the string, leaving the ones in middle of string.
I've asked similar question here, and good solution is:
$str = preg_replace('/^\W*(.*\w)\W*$/', '$1', $str);
But it does remove also some signs like ąĄćĆęĘ etc and it should not as its still alphabetical sign.
Above example would do:
~~AAA~~ => AAA (OK)
~~AA*AA~~ => AA*AA (OK)
~~ŚAAÓ~~ => AA (BAD)
Make sure you use u flag for unicode while using your regex.
Following works with your input:
$str = preg_replace('/^\W*(.*\w)\W*$/u', '$1', '~~ŚAAÓ~~' );
// str = ŚAAÓ
But this won't work: (Don't Use it)
$str = preg_replace('/^\W*(.*\w)\W*$/', '$1', '~~ŚAAÓ~~' );
You can pass in a list of valid characters and tell the function to replace any character that is not in that list:
$str = preg_replace('/[^a-zA-Z0-9*]+/', '', $str);
The square brackets say select everything in this range. The carat (^) is the regex for not. We then list our valid characters (lower case a to z, uppercase a to z, numbers from 0 to 9, and an asterisks). The plus symbol on the end of the square bracket says select 0 or more characters.
Edit:
If this is the list of all characters you want to keep, then:
$str = preg_replace('/[^ĄąĆ毿ŹźŃńŁłÓó*]+/', '', $str);

How to remove a string between the specific characters using regular expression in PHP?

I have string like below,
$string = "test coontevt [gallery include=\"12,24\"] first [gallery include=\"12,24\"] second";
i need to remove the string starts with [gallery to first ocuurance of it's ].
i already use this one,
$string12 = preg_replace('/[gallery.+?)+(/])/i', '', $string);
but i get empty string only.
Finally i want result for the above string is,
$string ="test coontevt first second".
How can i do this using regular expression?.
plz help me?
The character [ is a regex meta-character. TO match a literal [ you need to escape it.
$string12 = preg_replace('/\[gallery.+?\]/i', '', $string);
or
$string12 = preg_replace('/\[gallery[^\]]+\]/i', '', $string);
You need to escape the square brackets
$string12 = preg_replace('/\[gallery.+?\]/i', '', $string);
The round brackets are unnecessary so I removed them, also the quantifier between those brackets and the forward slash before the last square bracket.
To avoid multiple space in the result, I would match also the surrounding spaces and replace with 1 space.
\s+\[gallery.+?\]\s+ and replace with one space
$string12 = preg_replace('/\s+\[gallery.+?\]\s+/i', ' ', $string);
See this expression here online on Regexr
Try it like this:
$string12 = preg_replace('/\[gallery[^\]]+\]/i', '', $string);
[^\]]+ means that there can be one or more character that is not ]. And there is no need for any ( and ) if you don't want to use the backreferences.

Categories