Laravel 8 how to parse template variables in string - php

I have a string that contains multiple templated variables like this:
$str = "Hello ${first_name} ${last_name}";
How can I do to extract these variables in an array like this :
$array = ['first_name', 'last_name'];

Use single quotes instead of double quotes when describing the string.
$str = 'Hello ${first_name} ${last_name}';
preg_match_all('/{(.*?)}/s', $str, $output_array);
dd($output_array[1]);

Use explode function example given below:
$str = "Hello ${first_name} ${last_name}";
$str_to_array = explode("$",$str);
$array = array();
foreach($str_to_array as $data){
if (str_contains($data, '{')) {
$array[] = str_replace("}","",str_replace("{","",$data));
}
}
print_r($array);

You can use a simple regular expression and use preg_match_all to find all the ocurrences, like this:
<?php
$pattern = '|\${.*?}|';
$subject = 'Hello ${first_name} ${last_name}';
$matches = '';
preg_match_all($pattern, $subject, $matches);
print_r($matches);
?>
Result:
Array
(
[0] => Array
(
[0] => ${first_name}
[1] => ${last_name}
)
)

Related

Split String contain Brackets in PHP

I have string like following format:
$string ='[(id,name,top,left,width,height,depth)filename|filename][(id,name,top,left,width,height,depth)filename|filename]';
I want to extract string for square and simple bracket and result set would be like
[0] =>(id,name,top,left,width,height,depth)
[1] => filename
[2] => filename
How can i do it? I have tried below code:
explode("[" , rtrim($string, "]"));
But not working properly.
You can use regex for this,
$re = "/\\[\\((.*?)\\)(.*?)\\]/s";
$str = "[(id,name,top,left,width,height,depth)filename|filename][(id,name,top,left,width,height,depth)filename|filename]'";
preg_match_all($re, $str, $matches);
output
matches[1][0] => id,name,top,left,width,height,depth
matches[1][1] => filename|filename
See
regex
Use this code
$string ='[(id,name,top,left,width,height,depth)filename|filename][(id,name,top,left,width,height,depth)filename|filename]';
$array = explode('][',$string);
$array = array_unique(array_filter($array));
$singleArr = array();
$singleArr[] = str_replace('[','',$array['0']);
$singleArr[] = str_replace(']','',$array['1']);
$singleArr = array_unique($singleArr);
//print_r($singleArr);
$blankArr = array();
foreach($singleArr as $val)
{
$first = explode('|',$val);
$blankArr['0'] = substr($first['0'],0,-8);
$blankArr['1'] = substr($first['0'],-8);
$blankArr['2'] = $first['1'];
}
print_r($blankArr);

How to get an array from string, containing an array?

Is it possible to using a regular expression, or otherwise create a function that will convert a string containing the php array of any form, in the real array, which can operate?
For Example:
$str = "array(1, array(2), array('key' => 'value'))";
$arr = stringArrayToArray($str);
Maybe there is already such an implementation of task?
Or do not bother, but simply to use eval()?
$arr = eval("return $str;");
You can try explode() function.
Try it.
<?php
$str = "do you love me";
$arr = explode(' ', $str);
print_r($arr);
?>
You can just replace the array( with a [ and ) with ]
as shown below:
$str = "array(1, array(2), array('key' => 'value'))";
$str = str_replace(" ","",str_replace(",","[",$str));
$str = str_replace(")","",str_replace("array(","[",$str));
echo $str;
$arr = explode("[",$str);
var_dump($arr);
?>
this the best I could get.

preg replace for needed value

I use coordinates for shops and manually add the coordinates as lang and long to database. Sometimes by mistake, approving the coordinate.
Let me exlain by an example.
For example;
Lang is 33.4534543543 .But by mistake sometimes i push keyboard and it becomes like,
33.4534543543<
or
33.4534543543,
or
,(space)33.4534543543<
How can I get only the 33.4534543543?
preg_match_all
To find matches from a string containing multiple matches, you would use preg_match_all:
$strings = "33.4534543543<
33.4534543543,
, 33.4534543543<";
$pattern = "!(\d+\.\d+)!";
preg_match_all($pattern,$strings,$matches);
print_r($matches[0]);
Output
Array
(
[0] => 33.4534543543
[1] => 33.4534543543
[2] => 33.4534543543
)
preg_match
To find the match from a single string you could use preg_match.
$string = "33.4534543543<";
$pattern = "!(\d+\.\d+)!";
if(preg_match($pattern,$string,$match)){
print($match[0]);
}
Output
33.4534543543
preg_replace
To replace anything that is not what you want in your existing string you would use preg_replace:
$string = preg_replace('![^\d.]!','',$string);
An example:
$strings = "33.4534543543<
33.4534543543,
, 33.4534543543<";
$strings_exp = explode("\n",$strings);
$output = '';
foreach($strings_exp as $string){
$output.= "String '$string' becomes ";
$new_string = preg_replace('![^0-9.]!','',$string);
$output.= "'$new_string'\n";
}
echo $output;
output
String '33.4534543543<' becomes '33.4534543543'
String '33.4534543543,' becomes '33.4534543543'
String ', 33.4534543543<' becomes '33.4534543543'
Sound like you want to do a preg_match: http://phpfiddle.org/main/code/z6q-a1d
$old_vals = array(
'33.4534543543<',
'33.4534543543,',
', 33.4534543543<'
);
$new_vals = array();
foreach ($old_vals as $val) {
preg_match('(\d*\.?\d+)',$val, $match);
array_push($new_vals, $match[0]);
}
print_r($new_vals);
Output
Array (
[0] => 33.4534543543,
[1] => 33.4534543543,
[2] => 33.4534543543
)

Split string using regular expression in php

I'm beginner in php and I have string like this:
$test = http://localhost/biochem/wp-content/uploads//godzilla-article2.jpghttp://localhost/biochem/wp-content/uploads/life-goes-on-wpcf_300x111.jpg
And I want to split string to array like this:
Array(
[0] => http://localhost/biochem/wp-content/uploads//godzilla-article2.jpg
[1] => http://localhost/biochem/wp-content/uploads/life-goes-on-wpcf_300x111.jpg
)
What should I do?
$test = 'http://localhost/biochem/wp-content/uploads//godzilla-article2.jpghttp://localhost/biochem/wp-content/uploads/life-goes-on-wpcf_300x111.jpg';
$testurls = explode('http://',$test);
foreach ($testurls as $testurl) {
if (strlen($testurl)) // because the first item in the array is an empty string
$urls[] = 'http://'. $testurl;
}
print_r($urls);
You asked for a regex solution, so here you go...
$test = "http://localhost/biochem/wp-content/uploads//godzilla-article2.jpghttp://localhost/biochem/wp-content/uploads/life-goes-on-wpcf_300x111.jpg";
preg_match_all('/(http:\/\/.+?\.jpg)/',$test,$matches);
print_r($matches[0]);
The expression looks for parts of the string the start with http:// and end with .jpg, with anything in between. This splits your string exactly as requested.
output:
Array
(
[0] => http://localhost/biochem/wp-content/uploads//godzilla-article2.jpg
[1] => http://localhost/biochem/wp-content/uploads/life-goes-on-wpcf_300x111.jpg
)
you can split them if they are always like this vith substr() function reference: http://php.net/manual/en/function.substr.php but if they are dynamic in lenght. you need to get a ; or any other sign that is not likely to be used there before 2nd "http://" and then use explode function reference: http://php.net/manual/en/function.explode.php
$string = "http://something.com/;http://something2.com"; $a = explode(";",$string);
Try the following:
<?php
$temp = explode('http://', $test);
foreach($temp as $url) {
$urls[] = 'http://' . $url;
}
print_r($urls);
?>
$test = 'http://localhost/biochem/wp-content/uploads//godzilla-article2.jpghttp://localhost/biochem/wp-content/uploads/life-goes-on-wpcf_300x111.jp';
array_slice(
array_map(
function($item) { return "http://" . $item;},
explode("http://", $test)),
1);
For answering this question by regular expression I think you want something like this:
$test = "http://localhost/biochem/wp-content/uploads//godzilla-article2.jpghttp://localhost/biochem/wp-content/uploads/life-goes-on-wpcf_300x111.jpg";
$keywords = preg_split("/.http:\/\//",$test);
print_r($keywords);
It returns exactly something you need:
Array
(
[0] => http://localhost/biochem/wp-content/uploads//godzilla-article2.jp
[1] => localhost/biochem/wp-content/uploads/life-goes-on-wpcf_300x111.jpg
)

PHP - Using explode() function to assign values to an associative array

I'd like to explode a string, but have the resulting array have specific strings as keys rather than integers:
ie. if I had a string "Joe Bloggs", Id' like to explode it so that I had an associative array like:
$arr['first_name'] = "Joe";
$arr['last_name'] = "Bloggs";
at the moment, I can do:
$str = "Joe Bloggs";
$arr['first_name'] = explode(" ", $str)[0];
$arr['last_name'] = explode(" ", $str)[1];
which is inefficient, because I have to call explode twice.
Or I can do:
$str = "Joe Bloggs";
$arr = explode(" ", $str);
$arr['first_name'] = $arr[0];
$arr['last_name'] = $arr[1];
but I wonder if there is any more direct method.
Many thanks.
I would use array_combine like so:
$fields = array ( 'first_name', 'last_name' );
$arr = array_combine ( $fields, explode ( " ", $str ) );
EDIT: I would also pick this over using list() since it allows you to add fields should you require without making the list() call unnecessarily long.
You can make use of list PHP Manual (Demo):
$str = "Joe Bloggs";
list($arr['first_name'], $arr['last_name']) = explode(" ", $str);
$arr then is:
Array
(
[last_name] => Bloggs
[first_name] => Joe
)
You cannot do explode(" ", $str)[0] in PHP <= 5.3.
However, you can do this:
list($arr['first_name'], $arr['last_name']) = explode(" ", $str);

Categories