Regular Expressions to replace {{a,b}} and {{a}} - php

I have many strings. Some examples are shown below:
This is my first example string. {{1}} This is what it looks like.
This is my second example string. {{1,2}}. This is what it looks like.
This is my third example string. {{1,3}} and {{2}}. This is what it looks like.
My code needs to replace each token that looks like {{1}} with <input name="var1">
It also needs to replace each token that looks like {{1,2}} with <input name="var1" value="2">
In general, each token that looks like {{a}} needs to be replaced with <input name="vara"> and each token that looks like {{a,b}} with <input name="vara" value="b">
I am using php.
What would be the best way to do this. There will be many "tokens" to replace within each string. And each string can have tokens of both styles.
Right now, my code looks like this:
for ($y = 1; $y < Config::get('constants.max_input_variables'); $y++) {
$main_body = str_replace("{{" . $y . "}}", "<input size=\"5\" class=\"question-input\" type=\"text\" name=\"var" . $y . "\" value=\"".old('var'.$y)."\" >", $main_body);
}
But this is obviously not very efficient since I cycle through looking for matches. And ofcourse, I am not even matching the tokens that look like {{1,2}}

Use regex \{\{(\d+)(,(\d+))?\}\}
Regex Explanation and Live Demo
\{: Matches { literally, need to escape as it is special symbol in regex
(\d+): Matches one or more digits, captured in group 1
(,(\d+))?: Matches one or more digits followed by comma optionally
\}: Matches } literally
$1 and $3 are used in the replacement to get the first and third captured group respectively.
Example Code Usage:
$re = "/\\{\\{(\\d+)(,(\\d+))?\\}\\}/mi";
$str = "This is my first example string. {{1}} This is what it looks like.\nThis is my second example string. {{1,2}}. This is what it looks like.\nThis is my third example string. {{1,3}} and {{2}}. This is what it looks like.";
$subst = "<input name=\"var$1\" value=\"$3\" />";
$result = preg_replace($re, $subst, $str);

You need to use a callback:
$str = preg_replace_callback('/{{([^},]+)(?:,([^}]+))?}}/', function($_) {
return '<input name="var'.$_[1].'"' . (isset($_[2]) ? ' value="'.$_[2]. '"' : '') . '>';
}, $str);
See demo at eval.in
The regex {{([^},]+)(?:,([^}]+))?}} can be tried at regex101. Negated class [^},] matches characters that neither } nor ,. + one ore more. The second part (?:,([^}]+))? is optional.

you can use str_replace to get the number.
$str = str_replace(array('{{', '}}'), '' , '{{12,13}}');
output $str:
$str = '12,13';
then, use $arr = explode(',', $str), you can get the two number: 12 and 13
so the <input>. just use $arr[0] to fill in name and $arr[1] to fill in value.
the all codes:
$str = str_replace(array('{{', '}}'), '' , '{{12,13}}');
$arr = explode(',', str);
return '<input name="var'.$arr[0].'" value="'.$arr[1].'" />';

Related

REGEX match two patterns between specific characters

I know the title may be a little vague but I wasnt sure how to formulate it. I have a string that contains text that looks something like this:
$data["key1"] = "value1";
$data["key2"] = "value2";
$data["key3"] = "value3";
$data["key4"] = "value4";
I would like to match everything after $data[" and ]" and everything in between = " and "; in the same match, so for example the results would be
Match 1 = {key1, value1}
Match 2 = {key2, value2}
Match 3 = {key3, value3}
Match 4 = {key4, value4}
So far I have been able to match the values with
/(?<=]\s=\s\")(.*?)(?=\s*\"\;)/
but I would also need the first part in the result as well and I'm not sure how to do so.
Also, is there a way to have it match if there is (or isn't) white spaces between characters?
for example
$data["key1"]= "value1";
$data["key2"]="value2";
$data["key3"] ="value3";
$data["key4"] ="value4" ;
Would also all match the same thing?
Try using preg_match_all:
$input = '$data["key1"] = "value1";';
preg_match_all('/\$\w+\["(.*?)"\]\s*=\s*"(.*?)";/', $input, $matches);
echo "Match = {" . $matches[1][0] . ", " . $matches[2][0] . "}";
This prints:
Match = {key1, value1}
You can try the following for each line. Basically you just need to search for each pair of quotes in each line should do the work.
// $output_array is an array which the first index is your key and second is the value
// for example, array( "key1", "value1")
$input_lines = '$data["key1"] = "value1"';
preg_match_all('/\"\w+\"/', $input_lines, $output_array);

Search and replace all lines in a multiline string

I have a string with a large list with items named as follows:
str = "f05cmdi-test1-name1
f06dmdi-test2-name2";
So the first 4 characters are random characters. And I would like to have an output like this:
'mdi-test1-name1',
'mdi-test2-name2',
As you can see the first characters from the string needs to be replaced with a ' and every line needs to end with ',
How can I change the above string into the string below? I've tried for ours with 'strstr' and 'str_replace' but I can't get it working. It would save me a lot of time if I got it work.
Thanks for your help guys!
Here is a way to do the job:
$input = "f05cmdi-test1-name1
f05cmdi-test2-name2";
$result = preg_replace("/.{4}(\S+)/", "'$1',", $input);
echo $result;
Where \S stands for a NON space character.
EDIT : I deleted the above since the following method is better and more reliable and can be used for any possible combination of four characters.
So what do I do if there are a million different possibillites as starting characters ?
In your specific example I see that the only space is in between the full strings (full string = "f05cmdi-test1-name1" )
So:
str = "f05cmdi-test1-name1 f06dmdi-test2-name2";
$result_array = [];
// Split at the spaces
$result = explode(" ", $str);
foreach($result as $item) {
// If four random chars take string after the first four random chars
$item = substr($item, 5);
$result_array = array_push($result_arrray, $item);
}
Resulting in:
$result_array = [
"mdi-test1-name1",
"mdi-test2-name2",
"....."
];
IF you would like a single string in the style of :
"'mdi-test1-name1','mdi-test2-name2','...'"
Then you can simply do the following:
$result_final = "'" . implode("','" , $result_array) . "'";
This is doable in a rather simple regex pattern
<?php
$str = "f05cmdi-test1-name1
f05cmdi-test2-name2";
$str = preg_replace("~[a-z0-9]{1,4}mdi-test([0-9]+-[a-z0-9]+)~", "'mdi-test\\1',", $str);
echo $str;
Alter to your more specific needs

Remove string starting with something

How can I do the following with php?
This is my example:
http://www.example.com/index.php?&xx=okok&yy=no&bb=525252
I want remove this part: &yy=no&bb=525252
I just want this result:
http://www.example.com/index.php?&xx=okok
I tried this :
$str = 'bla_string_bla_bla_bla';
echo preg_replace('/bla_/', '', $str, 1); ;
but this not what I want.
Going for preg_replace was a good start. But you need to learn about regexes.
This will work:
$str = 'http://www.example.com/index.php?&xx=okok&yy=no&bb=525252';
echo preg_replace ('/&yy.+$/', '', $str);
Here the regex is &yy.+$
Let's see how this works:
&yy matches &yy obviously
.+ matches everything ...
$ ... until the end of the string.
So here, my replacement says : Replace whatever begins by &yy until the end of the string by nothing, which is actually simply deleting this part.
You can do this:
$a = 'http://www.example.com/index.php?&xx=okok&yy=no&bb=525252';
$b = substr($a,0,strpos($a,'&yy')); // Set in '&yy' the string to identify the beginning of the string to remove
echo $b; // Will print http://www.example.com/index.php?&xx=okok
Are you always expecting the end part to have the 'yy' variable name? You could try this:
$str = 'http://www.example.com/index.php?&xx=okok&yy=no&bb=525252';
$ex = explode('&yy=', $str, 2);
$firstPart = $ex[0];

How to create an hyperlink in a paragraph using php

I would like to create hyperlinks to the words in a paragraph.
For instance if the "Jim Carrey" name is in the array matches the word in string, then the Jim Carrey name should be in Hyperlink of "www.domian.net/name(Jim Carrey)" .
If the "mask" word in the array matches the word in string then it should be replace with corresponding url like "www.domian.net/mask"
<?php
$string="Jim Carrey found the new Mask";
$array=array("Jim Carrey","mask");
echo preg_replace( '/\b('.implode( '|', $array ).')\b/i', '$1', $string );
?>
You seem to have the right idea about how to put a link around the chosen text, but you seem to have not even tried to put in an href. Which is a shame, since it's as simple as typing in the URL with whatever parameter you want.
However, it does get a little complicated because you don't want the same thing both times (you want the literal word in one, but you want name(WORD) in the other). You could try this:
$array = array("Jim Carrey"=>"name(Jim Carrey)","mask"=>"mask");
echo preg_replace_callback("/\b".implode("|",array_keys($array))."\b/i",
function($m) use ($array) {
return "".$m."";
},$string);
<?php
$string="Jim Carrey found the new Mask";
$arr=array("Jim Carrey","Mask");
foreach($arr as $val)
$string = str_replace($val, '' . $val . '', $string);
echo $string;
?>

Increment integer at end of string

I have a string, "Chicago-Illinos1" and I want to add one to the end of it, so it would be "Chicago-Illinos2".
Note: it could also be Chicago-Illinos10 and I want it to go to Chicago-Illinos11 so I can't do substr.
Any suggested solutions?
Complex solutions for a really simple problem...
$str = 'Chicago-Illinos1';
echo $str++; //Chicago-Illinos2
If the string ends with a number, it will increment the number (eg: 'abc123'++ = 'abc124').
If the string ends with a letter, the letter will be incremeted (eg: '123abc'++ = '123abd')
Try this
preg_match("/(.*?)(\d+)$/","Chicago-Illinos1",$matches);
$newstring = $matches[1].($matches[2]+1);
(can't try it now but it should work)
$string = 'Chicago-Illinois1';
preg_match('/^([^\d]+)([\d]*?)$/', $string, $match);
$string = $match[1];
$number = $match[2] + 1;
$string .= $number;
Tested, works.
explode could do the job aswell
<?php
$str="Chicago-Illinos1"; //our original string
$temp=explode("Chicago-Illinos",$str); //making an array of it
$str="Chicago-Illinos".($temp[1]+1); //the text and the number+1
?>
I would use a regular expression to get the number at the end of a string (for Java it would be [0-9]+$), increase it (int number = Integer.parse(yourNumberAsString) + 1), and concatenate with Chicago-Illinos (the rest not matched by the regular expression used for finding the number).
You can use preg_match to accomplish this:
$name = 'Chicago-Illinos10';
preg_match('/(.*?)(\d+)$/', $name, $match);
$base = $match[1];
$num = $match[2]+1;
print $base.$num;
The following will output:
Chicago-Illinos11
However, if it's possible, I'd suggest placing another delimiting character between the text and number. For example, if you placed a pipe, you could simply do an explode and grab the second part of the array. It would be much simpler.
$name = 'Chicago-Illinos|1';
$parts = explode('|', $name);
print $parts[0].($parts[1]+1);
If string length is a concern (thus the misspelling of Illinois), you could switch to the state abbreviations. (i.e. Chicago-IL|1)
$str = 'Chicago-Illinos1';
echo ++$str;
http://php.net/manual/en/language.operators.increment.php

Categories