How to add single quote with Regex php arrays - php

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']

Related

simple preg_replace() not working right for me :/

$str = "{Controller}/{Action}";
$str = preg_replace("/\//","\\/",$str);
$str = preg_replace("/(\{\w+\})\\/(\{\w+\})/","\\1 slash \\2",$str);
echo $str;
So the third line doesn't do anything for me, could anyone say where i was wrong? It works if i put something else instead of \/
thanks in advance;)
This will work:
$str = "{Controller}/{Action}";
$str = preg_replace('#(\{\w+\})/(\{\w+\})#', '\1 slash \2', $str);
echo $str;
Output: {Controller} slash {Action}
Remarks:
You should use single quotes to reduce the need for escaping and therefore much better readability.
You also should consider using another delimiter if you are matching literal slashes (eg #, but anything works)

How to remove the double quotes from json string except the first json value?

Please help me.
Here my json input.
{"id":"FWAX014","price":18,"quantity":1}
Expected output should be like this:
{id:"FWAX014",price:18,quantity:1}
Thanks in advance.
The following regex removes the double quotes you want:
(?<={|,)"(\w+)"
See the demo
Explanation
(?<={|,) checks that the following pattern is preceded by a curly brace or a comma
"(\w+)" matches the word between the quotes
Example
$re = '/(?<={|,)"(\w+)"/';
$str = '{"id":"FWAX014","price":18,"quantity":1}';
$result = preg_replace($re, '$1', $str);

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.

PHP Remove spaces and %20 within single function

I wish to remove white space from a string. The string would have ben urlencoded() prior, so I also wish to remove %20 too. I can do this using two separate functions, but how do i do this with one function?
$string = str_replace("%20","",$string);
$string = str_replace(" ","",$string);
You could use preg_replace function.
preg_replace('~%20| ~', "", $string)
Don't use a regex for that but strtr:
$result = strtr($str, array('%20'=>'', ' '=>''));

Erasing multiple symbols from a string

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.

Categories