Erasing multiple symbols from a string - php

I know that preg_replace('/[{}]/', '', $string); will erase curly brackets, but what if I had square brackets too and also needed to erase them?

Why go through the trouble of using regex for this. If all you're doing is replacing 4 chars from a string:
str_replace(array('[',']','{','}'),'',$string);
Will do the same thing.

include square brackets (escaped) into the character class: /[{}\[\]]/

preg_replace('/[{}\[\]]/', '', $string);
You should add them with proper escaping to class in Regex
$string = 'asdf{[]a]}ds';
echo preg_replace('/[{}\[\]]/', '', $string);
Output: asdfads

You'd have to escape it:
/[{}[\]]/

As you are looking for a square bracket removal:
$str = preg_replace("/\[([^\[\]]++|(?R))*+\]/", "", $str);
That will convert this:
This [text [more text]] is cool
to this:
This is cool
EDIT
$string = '<p>hey</p><p>[[{"type":"media","view_mode":"media_large","fid":"67","attributes":{"alt":"","class":"media-image","height":"125","typeof":"foaf:Image","width":"125"}}]]</p>';
$new_string = preg_replace('/\[\[.*?\]\]/', '<b>img inserted</b>', $string);
echo $new_string;
let me know if i can help you further.

Related

How to add single quote with Regex php arrays

For From
$data[ContactInfos][ContactInfo][Addresses]
to
$data['ContactInfos']['ContactInfo']['Addresses']
Try the following regex(Demo):
(?<=\[)|(?=\])
PHP(Demo):
preg_replace('/(?<=\[)|(?=\])/', "'", $str);
With this
preg_replace('/\[([^\]]+)\]/', "['\1']", $input);
Try it here
https://regex101.com/r/YTIOWY/1
If you have mixed string - with and without quote, regex must be a little sophysticated
$str = '$data[\'ContactInfos\'][ContactInfo]["Addresses"]';
$str = preg_replace('/(?<=\[)(?!(\'|\"))|(?<!(\'|\"))(?=\])/', "'", $str);
// result = $data['ContactInfos']['ContactInfo']["Addresses"]
demo
The first rule of regex: "Don't use regex unless you have to."
This question doesn't require regex and the function call is not prohibitively convoluted. Search for square brackets, and write a single quote on their "inner" side.
Code (Demo)
$string='$data[ContactInfos][ContactInfo][Addresses]';
echo str_replace(['[',']'],["['","']"],$string);
Output:
$data['ContactInfos']['ContactInfo']['Addresses']

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

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

How to remove surrounding Square Brackets using php

I need a way to remove the surrounding square brackets from this using only php:
[txt]text[/txt]
So the result should be: text
They will always occur in matched pairs.
They always will be at the start and end of the string. Thet will always be [txt1][/txt1] or [url2][/url2]
How can i do it?
Try this:
preg_replace("/\[(\/\s*)?txt\d*\]/i", "", "[txt]text[/txt]");
Update:
This will work for "whatever" in the brackets:
preg_replace("/\[.+?\]/i", "", "[txt]text[/txt]");
You do not need to use regexp. You can explode the string on first ], after that use the result to explode on [.
Advantage using this method is that it is fast and simple.
If you simply need to get the text between square brackets of a simple structure, then try this:
$str = '[tag1]fdhfjdkf dfhjdkf[/tag1]';
$start_position = strpos($str, ']') + 1;
$end_postion = strrpos($str, '[');
$cleared = substr($str, $start_position, $end_postion - $start_position);
For more complicated structures this code won't work and you'll have to use some other ways.
You can use regex:
$string = '[whatever]content[/whatever]';
$pattern = '/\[[^\[\]]*\]/i';
$replacement = '';
echo preg_replace($pattern, $replacement, $string);
This will remove all [whatever] from a string.

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