Explode PHP String - php

I need some help, is it possible to explode like this?
I have a string 45-test-sample, is it possible to have
[0]=>string == "45"
[1]=>string == "test-sample"
How can it be done?

print_r(explode('-', $string, 2)); // take some help from the limit parameter
According to the PHP manual for explode
If limit is set and positive, the returned array will contain a maximum of limit elements with the last element containing the rest of string.
Output:
Array
(
[0] => 45
[1] => test-sample
)

Explode has a limit parameter.
$array = explode('-', $text, 2);

try this
$str = "45-test-sample";
$arr = explode('-', $str, 2);
print_r($arr);
OUTPUT :
Array
(
[0] => 45
[1] => test-sample
)
Demo

Try with exact output using list.
<?php
$str = "45-test-sample";
list($a,$b) = explode('-', $str, 2);
$arr=Array();
$arr=['0'=>"String == ".$a,'1'=>"String == ".$b];
print_r($arr);
?>
Output:
Array
(
[0] => String == 45
[1] => String == test-sample
)
DEMO

Related

PHP String(which contain array of object) to Array conversion

Suppose I have a string (which contain array of objects):
$string = "[{'test':'1', 'anothertest':'2'}, {'test':'3', 'anothertest':'4'}]";
My goals is to get the output to look like this when I print_r:
Array
(
[0] => Array
(
[test] => 1
[anothertest] => 2
)
[1] => Array
(
[test] => 3
[anothertest] => 4
)
)
I tried to json_decode($string) but it returned NULL
Also tried my own workaround which is kinda solved the problem,
$string = "[{'test':'1', 'anothertest':'2'}, {'test':'3', 'anothertest':'4'}]";
$string = substr($string, 1, -1);
$string = str_replace("'","\"", $string);
$string = str_replace("},","}VerySpecialSeparator", $string);
$arrayOfString = explode("VerySpecialSeparator",$string);
$results = [];
foreach($arrayOfString as $string) {
$results[] = json_decode($string, true);
}
echo "<pre>";
print_r($results);
die;
But is there any other ways to solve this?
As per your given data, if quotes will be corrected, then you will get your desired output, so get it done like below:
<?php
$string = "[{'test':'1', 'anothertest':'2'}, {'test':'3', 'anothertest':'4'}]";
$string = str_replace("'",'"', $string);
print_r(json_decode($string,true));
https://3v4l.org/PDI7O

Compare a string and a php array and only show the matches

I have a string that looks like this:
"illustration,drawing,printing"
I have an array that looks like this:
Array (
[0] => illustration
[1] => drawing
[2] => painting
[3] => ceramics
)
How can I compare the two and only display the terms that exist in both the string and array?
So in the above example, I would want to output something that looks like this:
SKILLS: illustration, drawing
Thank you!
use explode(), array_intersect() and implode()
<?php
$string = "illustration,drawing,printing";
$array = Array (
0 => 'illustration',
1 => 'drawing',
2 => 'painting',
3 => 'ceramics'
);
$stringArray = explode(',',$string);
$common = array_intersect($stringArray,$array);
echo "Skills :".implode(',',$common);
https://3v4l.org/StqYN
You can do something like this:
Function:
function functionName($string, $array){
$skills = '';
// Create a temp array from your string breaking appart from the commas
$temparr = explode(",", $string);
// Iterate through each of the words now
foreach($temparr as $str){
// Check to see if our current string is in the array provided
if(in_array($str, $array)){
// If it is, then add it to the string "skills"
$skills .= "${str}, ";
}
}
// Cut the last space and comma off the end of the str.
$skills = substr($skills, 0, strlen($skills) - 2);
// Return our results
return 'SKILLS: '.$skills;
}
Usage:
$string = "illustration,drawing,printing";
$array = Array (
0 => "illustration",
1 => "drawing",
2 => "painting",
3 => "ceramics"
);
// Just input our string and the array we want to search through
echo(functionName($string, $array));
Live Demos:
https://ideone.com/qyqgzo
http://sandbox.onlinephpfunctions.com/code/65dc988370ad8ce61ab5ccbc232af4bcf8bd3d42
You could replace the comma , and join the string words on OR | and grep for them. This will match the word anywhere in each array element:
$result = preg_grep("/".str_replace(",", "|", $string)."/", $array);
If you want exact matches only then: "/^(".str_replace(",", "|", $string).")$/"
Firstly convert that string into array.
use array_intersect();
$str = "illustration,drawing,printing";
$ar1 = explode(",",$str);
print_r ($ar1);
$ar2 = Array ("illustration","drawing","painting","ceramics");
echo "<br>";
print_r ($ar2);
$result = array_intersect($ar1, $ar2);
echo "Skills :".implode(',',$result);
OUTPUT:
Array (
[0] => illustration
[1] => drawing
[2] => printing
)
Array (
[0] => illustration
[1] => drawing
[2] => painting
[3] => ceramics
)
SKILLS: illustration, drawing

separate special characters from numbers in string in php

I have $value = "10,120,152" in string, now i want to put each number in separate variable like $a = 10; $b = 120; $c = 152;
so basically what i am asking is that how to separate , from the numbers in a string.
If the separator is always a , than using explode makes sense. If the separator varies though you could use a regex.
$value = "10,120,152";
preg_match_all('/(\d+)/', $value, $matches);
print_r($matches[1]);
Output:
Array
(
[0] => 10
[1] => 120
[2] => 152
)
Demo: https://eval.in/483906
That \d+ is all continuos numbers.
Regex101 Demo: https://regex101.com/r/rP2bV1/1
A third approach would be using str_getcsv.
$value = "10,120,152";
$numbers = str_getcsv($value, ',');
print_r($numbers);
Output:
Array
(
[0] => 10
[1] => 120
[2] => 152
)
Demo: https://eval.in/483907
$exploded = explode("," , $values);
var_dump($exploded);
Explode(string $delimiter , string $string [, int $limit ])
You can use explode(), it will return an array with the numbers.
$array = explode(',', $value);
Check this one using list
$value = "10,120,152";
$variables = explode("," , $values);
$variables = array_map('intval', $variables);//If you want integers add this line
list($a, $b, $c) = $variables;

What is the best way to split letters and numbers?

I have this variable:
$str = "w15";
What is the best way to split it to w and 15 separately?
explode() is removing 1 letter, and str_split() doesn't have the option to split the string to an unequal string.
$str = "w15xx837ee";
$letters = preg_replace('/\d/', '', $str);
$numbers = preg_replace('/[^\d]/', '', $str);
echo $letters; // outputs wxxee
echo $numbers; // outputs 15837
You could do something like this to separate strings and numbers
<?php
$str = "w15";
$strarr=str_split($str);
foreach($strarr as $val)
{
if(is_numeric($val))
{
$intarr[]=$val;
}
else
{
$stringarr[]=$val;
}
}
print_r($intarr);
print_r($stringarr);
Output:
Array
(
[0] => 1
[1] => 5
)
Array
(
[0] => w
)
If you want it to be as 15 , you could just implode the $intarr !
Use preg_split() to achieve this:
$arr = preg_split('~(?<=\d)(?=[a-zA-Z])|(?<=[a-zA-Z])(?=\d)~', $str);
Output:
Array
(
[0] => w
[1] => 15
)
For example, the string w15g12z would give the following array:
Array
(
[0] => w
[1] => 15
[2] => g
[3] => 12
[4] => z
)
Demo
Much cleaner:
$result = preg_split("/(?<=\d)(?=\D)|(?<=\D)(?=\d)/",$str);
Essentially, it's kind of like manually implementing \b with a custom set (rather than \w)

PHP string and number to an array

I have php var with multiple string values and numbers,
$string = 'Simple 12, Complex 16';
i explode this to an array, but i need to explode this string to be like below array.
Array(
[0] => Array(
[Simple] => 12,
[Complex] => 16
)
)
what is the perfect way to do this in php?
Here's a quick way:
preg_match_all('/(\w+)\s*(\d+)/', $str, $matches);
$result = array_combine($matches[1], $matches[2]);
<?php
$string = 'Simple 12, Complex 16';
$values=explode(",",$string);
$result=array();
foreach($values as $value)
{
$value=trim($value);
list($type,$count)=explode(" ",$value);
$result[0][$type]=$count;
}
print_r($result);
?>
Output
Array
(
[0] => Array
(
[Simple] => 12
[Complex] => 16
)
)
Demo
Do like this, if you want to get out put like this.
<?PHP
$string = 'Simple 12, Complex 16';
$my_arr1 = explode(',',$string);
foreach ($my_arr1 as $value) {
$value=trim($value);
$my_arr2 = explode(' ',$value);
$final_array[$my_arr2[0]]=$my_arr2[1];
}
print_r($final_array);
OUTPUT
Array
(
[Simple] => 12
[Complex] => 16
)
<?php
preg_match_all("/[A-Za-z]+/","Simple 12, Complex 16",$keys);
preg_match_all("/[0-9]{2}/","Simple 12, Complex 16",$vals);
$a = array_combine($keys[0],$vals[0]);
print_r($a);
try it out
The reply from user "Ø Hanky Panky Ø", have an error:
Here:
$result[0][$type]=$count;
Correctly is:
$result[][$type]=$count;
preg_match_all('/(\w+)\s*(\d+)/', $string, $matc);
$output = array_combine($match[1], $match[2]);

Categories