i want to make a php loop that puts the values from a string in 2 different variables.
I am a beginner. the numbers are always the same like "3":"6" but the length and the amount of numbers (always even). it can also be "23":"673",4:6.
You can strip characters other than numbers and delimiters, and then do explode to get an array of values.
$string = '"23":"673",4:6';
$string = preg_replace('/[^\d\:\,]/', '', $string);
$pairs = explode(',', $string);
$pairs_array = [];
foreach ($pairs as $pair) {
$pairs_array[] = explode(':', $pair);
}
var_dump($pairs_array);
This gives you:
array(2) {
[0]=>
array(2) {
[0]=>
string(2) "23"
[1]=>
string(3) "673"
}
[1]=>
array(2) {
[0]=>
string(1) "4"
[1]=>
string(1) "6"
}
}
<?php
$string = '"23":"673",4:6';
//Remove quotes from string
$string = str_replace('"','',$string);
//Split sring via comma (,)
$splited_number_list = explode(',',$string);
//Loop first list
foreach($splited_number_list as $numbers){
//Split numbers via colon
$splited_numbers = explode(':',$numbers);
//Numbers in to variable
$number1 = $splited_numbers[0];
$number2 = $splited_numbers[1];
echo $number1." - ".$number2 . "<br>";
}
?>
Related
i have elements in my php array who contain   elements , i try to remove the elements who contain only space ( ), so i apply on my array:
$steps = array_map( 'html_entity_decode', $steps);
$steps = array_map('trim',$steps);
$steps = array_filter($steps, 'strlen'); //(i try also array_filter($steps);
but the elements reside.
Any idea please
Try this:
/**
* Function to strip away a given string
**/
function remove_nbsp($string){
$string_to_remove = " ";
return str_replace($string_to_remove, "", $string);
}
# Example data array
$steps = array("<p>step1</p>", "<p>step2</p>", "<p>step3</p>", "<p> </p>", " ", "<p> </p>", "<p>step4</p>");
$steps = array_map("strip_tags", $steps);
//Strip_tags() will remove the HTML tags
$steps = array_map("remove_nbsp", $steps);
//Our custom function will remove the character
$steps = array_filter($steps);
//Array_filter() will remove any blank array values
var_dump($steps);
/**
* Output:
array(4) {
[0]=>
string(5) "step1"
[1]=>
string(5) "step2"
[2]=>
string(5) "step3"
[6]=>
string(5) "step4"
}
*/
You might even find it easier to do a foreach():
foreach($steps as $dirty_step){
if(!$clean_step = trim(str_replace(" ", "", strip_tags($dirty_step)))){
//Ignore empty steps
continue;
}
$clean_steps[] = $clean_step;
}
I'm trying to create an if statement. based on the string of the
$var = "Apple : Banana";
$array = explode(":", $var);
print_r($array); //array([0] => 'Apple' [1] => 'Banana')
if ($array[1] == "Banana") {
echo "Banana!";
}
The string has space before and after :, so array will be
array(2) {
[0]=> string(6) "Apple "
[1]=> string(7) " Banana"
}
You need to remove space from items using trim() and then compare it.
$var = "Apple : Banana";
$array = explode(":", $var);
if (trim($array[1]) == "Banana") {
echo "Banana!";
}
Your condition doesn't work because each element of array has space. You should remove excess spaces. You can use trim function to remove spaces and array_map function to apply trim in each element of the array.
For example:
$var = "Apple : Banana";
$array = array_map('trim', explode(":", $var));
if ($array[1] == "Banana") {
echo "Banana!";
}
result:
Banana!
You can do it by using preg_split and regex
$parts = preg_split('/\s+\:\s+/', $var);
Then on $parts you will get:
array(2) { [0]=> string(5) "Apple" [1]=> string(6) "Banana" }
Im trying to extract a specific value from multiple strings. Lets say i have the following strings:
/a-url/{some_hash}/
/user/{user_hash}/
/user-overview/{date_hash}/{user_hash}
I want to extract all between curly bracket open and _hash}, how can i achieve this?
The output should be a array:
$array = [
'some_hash',
'user_hash',
'date_hash',
'user_hash'
];
Current code:
$matches = [];
foreach (\Route::getRoutes()->getRoutes() as $route) {
$url = $route->getUri();
preg_match_all('/({.*?_hash})/', $url, $matches);
}
You can use regex for that:
$s = '/a-url/{some_hash}/
/user/{user_hash}/
/user-overview/{date_hash}/{user_hash}';
preg_match_all('/{(.*?_hash)}/', $s, $m);
var_dump($m[1]);
The output will be:
array(4) {
[0]=>
string(9) "some_hash"
[1]=>
string(9) "user_hash"
[2]=>
string(9) "date_hash"
[3]=>
string(9) "user_hash"
}
Based on your edit you probably want:
$all_matches = [];
foreach (\Route::getRoutes()->getRoutes() as $route) {
$url = $route->getUri();
preg_match_all('/{(.*?_hash)}/', $url, $matches);
$all_matches = array_merge($all_matches, $matches[1]);
}
var_dump($all_matches);
This is my string: $string="VARHELLO=helloVARWELCOME=123qwa";
I want to get 'hello' and '123qwa' from string.
My pseudo code is.
if /^VARHELLO/ exist
get hello(or whatever comes after VARHELLO and before VARWELCOME)
if /^VARWELCOME/ exist
get 123qwa(or whatever comes after VARWELCOME)
Note: values from 'VARHELLO' and 'VARWELCOME' are dynamic, so 'VARHELLO' could be 'H3Ll0' or VARWELCOME could be 'W3l60m3'.
Example:
$string="VARHELLO=H3Ll0VARWELCOME=W3l60m3";
Here is some code that will parse this string out for you into a more usable array.
<?php
$string="VARHELLO=helloVARWELCOME=123qwa";
$parsed = [];
$parts = explode('VAR', $string);
foreach($parts AS $part){
if(strlen($part)){
$subParts = explode('=', $part);
$parsed[$subParts[0]] = $subParts[1];
}
}
var_dump($parsed);
Output:
array(2) {
["HELLO"]=>
string(5) "hello"
["WELCOME"]=>
string(6) "123qwa"
}
Or, an alternative using parse_str (http://php.net/manual/en/function.parse-str.php)
<?php
$string="VARHELLO=helloVARWELCOME=123qwa";
$string = str_replace('VAR', '&', $string);
var_dump($string);
parse_str($string);
var_dump($HELLO);
var_dump($WELCOME);
Output:
string(27) "&HELLO=hello&WELCOME=123qwa"
string(5) "hello"
string(6) "123qwa"
Jessica's answer is perfect, but if you want to get it using preg_match
$string="VARHELLO=helloVARWELCOME=123qwa";
preg_match('/VARHELLO=(.*?)VARWELCOME=(.*)/is', $string, $m);
var_dump($m);
your results will be $m[1] and $m[2]
array(3) {
[0]=>
string(31) "VARHELLO=helloVARWELCOME=123qwa"
[1]=>
string(5) "hello"
[2]=>
string(6) "123qwa"
}
I have a string having 128 values in the form of :
1,4,5,6,0,0,1,0,0,5,6,...1,2,3.
I want to pair in the form of :
(1,4),(5,6),(7,8)
so that I can make a for loop for 64 data using PHP.
You can accomplish this in these steps:
Use explode() to turn the string into an array of numbers
Use array_chunk() to form groups of two
Use array_map() to turn each group into a string with brackets
Use join() to glue everything back together.
You can use this delicious one-liner, because everyone loves those:
echo join(',', array_map(function($chunk) {
return sprintf('(%d,%d)', $chunk[0], isset($chunk[1]) ? $chunk[1] : '0');
}, array_chunk(explode(',', $array), 2)));
Demo
If the last chunk is smaller than two items, it will use '0' as the second value.
<?php
$a = 'val1,val2,val3,val4';
function x($value)
{
$buffer = explode(',', $value);
$result = array();
while(count($buffer))
{ $result[] = array(array_shift($buffer), array_shift($buffer)); }
return $result;
}
$result = x($a);
var_dump($result);
?>
Shows:
array(2) { [0]=> array(2) { [0]=> string(4) "val1" [1]=> string(4) "val2" } [1]=> array(2) { [0]=> string(4) "val3" [1]=> string(4) "val4" } }
If modify it, then it might help you this way:
<?php
$a = '1,2,3,4';
function x($value)
{
$buffer = explode(',', $value);
$result = array();
while(count($buffer))
{ $result[] = sprintf('(%d,%d)', array_shift($buffer), array_shift($buffer)); }
return implode(',', $result);
}
$result = x($a);
var_dump($result);
?>
Which shows:
string(11) "(1,2),(3,4)"