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)
Related
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
Say I have a list Poland,USA,England,China,Uruguay,Spain,Taiwan,Monaco.
I want to have a list starting on the 3rd item, and have 5 items in total. That means I want to have England,China,Uruguay,Spain,Taiwan.
How can I do this on PHP?
You can simply convert string to array like
$str = "Poland,USA,England,China,Uruguay,Spain,Taiwan,Monaco";
$array = explode(",",$str);
and then use array_slice to skip first 2 items
print_r(implode(",",array_slice($array,2)));
You can set limit to explode function (the 3rd argument) and get the last item of the result array
$str = 'Poland,USA,England,China,Uruguay,Spain,Taiwan,Monaco';
echo $result = explode(',', $str, 3)[2]; //England,China,Uruguay,Spain,Taiwan,Monaco
From the doc
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.
<?php
$list = "Poland,USA,England,China,Uruguay,Spain,Taiwan,Monaco";
$listArray = explode(",",$list);
print_r($listArray);
$startlist = 3; // Here you can set where you have start
if($startlist<count($listArray)){
print_r(implode(",",array_slice($listArray,$startlist)));
}else{
echo "Start limit exceed length of string";
}
?>
Output
For positive scenario set $startlist = 3;
Array
(
[0] => Poland
[1] => USA
[2] => England
[3] => China
[4] => Uruguay
[5] => Spain
[6] => Taiwan
[7] => Monaco
)
China,Uruguay,Spain,Taiwan,Monaco
for Negative scenario set $startlist = 8;
Array
(
[0] => Poland
[1] => USA
[2] => England
[3] => China
[4] => Uruguay
[5] => Spain
[6] => Taiwan
[7] => Monaco
)
Start limit exceed length of string
Just another way as a function, returns the new list if the new list can be returned, else returns false....
<?php
function formatList ( $l, $c, $s, $r )
{
$s -= 1;
$p = explode ( $c, $l );
return ( $r + $s ) <= count ( $p ) ? implode ( $c, array_slice ( $p, $s, $r ) ) : FALSE;
}
$list = 'Poland,USA,England,China,Uruguay,Spain,Taiwan,Monaco';
$split_on = ',';
$start_on = 3;
$return_total = 5;
echo formatList ( $list, $split_on, $start_on, $return_total ); // should be in a if(), just for example
?>
If you want to get your 5 items England,China,Uruguay,Spain,Taiwan, you could use explode in combination with array_slice and specify 2 for the offset and specify 5 for the length.
For example:
$str = "Poland,USA,England,China,Uruguay,Spain,Taiwan,Monaco";
$result = array_slice(explode(',', $str),2, 5)
print_r($result);
Result:
Array
(
[0] => England
[1] => China
[2] => Uruguay
[3] => Spain
[4] => Taiwan
)
See a php demo
Then you might also use implode to get the result as in your example:
echo implode(',', $result);
// England,China,Uruguay,Spain,Taiwan
I want to remove the numbers from array which have repeated digits in them.
array('4149','8397','9652','4378','3199','7999','8431','5349','7068');
to
array('8397','9652','4378','8431','5349','7068');
I have tried this thing
foreach($array as $key => $value) {
$data = str_split($value, 1);
$check = 0;
foreach($data as $row => $element) {
$check = substr_count($value, $element);
if($check != 1) {
array_diff($array, array($value));
}
}
}
You can filter the array using a regular expression that matches:
(.) any character
.* followed by zero or more characters
\1 followed by the first character one more time
Example code:
$array = array('4149','8397','9652','4378','3199','7999','8431','5349','7068');
$result = array_filter(
$array,
function ($number) {
return !preg_match('/(.).*\\1/', $number);
}
);
echo implode(', ', $result), PHP_EOL;
Output:
8397, 9652, 4378, 8431, 5349, 7068
This should work for you:
Here I first str_split() each element into a separate array with array_map(). After this I just compare the splitted array with the same array just with array_unique() digits and check if they are the same. If yes I return the implode() number otherwise false. And at the end I just filter the elements with false with array_filter() out.
So in other words I just compare these 2 arrays with they are the same:
array1:
Array
(
[0] => Array
(
[0] => 4
[1] => 1
[2] => 4
[3] => 9
)
//...
)
array2:
Array
(
[0] => Array
(
[0] => 4
[1] => 1
[3] => 9
)
//...
)
Code:
<?php
$arr = ['4149', '8397', '9652', '4378', '3199', '7999', '8431', '5349', '7068'];
$arr = array_map("str_split", $arr);
$result = array_filter(array_map(function($v1, $v2){
return ($v1 === $v2?implode("", $v1):false);
}, $arr, array_map("array_unique", $arr)));
print_r($result);
?>
output:
Array ( [1] => 8397 [2] => 9652 [3] => 4378 [6] => 8431 [7] => 5349 [8] => 7068 )
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
I need to split this kind of strings to separate the email between less and greater than < >. Im trying with the next regex and preg_split, but I does not works.
"email1#domain.com" <email1#domain.com>
News <news#e.domain.com>
Some Stuff <email-noreply#somestuff.com>
The expected result will be:
Array
(
[0] => "email1#domain.com"
[1] => email#email.com
)
Array
(
[0] => News
[1] => news#e.domain.com
)
Array
(
[0] => Some Stuff
[1] => email-noreply#somestuff.com
)
Code that I am using now:
foreach ($emails as $email)
{
$pattern = '/<(.*?)>/';
$result = preg_split($pattern, $email);
print_r($result);
}
You may use some of the flags available for preg_split: PREG_SPLIT_DELIM_CAPTURE and PREG_SPLIT_NO_EMPTY.
$emails = array('"email1#domain.com" <email1#domain.com>', 'News <news#e.domain.com>', 'Some Stuff <email-noreply#somestuff.com>');
foreach ($emails as $email)
{
$pattern = '/<(.*?)>/';
$result = preg_split($pattern, $email, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
print_r($result);
}
This outputs what you expect:
Array
(
[0] => "email1#domain.com"
[1] => email1#domain.com
)
Array
(
[0] => News
[1] => news#e.domain.com
)
Array
(
[0] => Some Stuff
[1] => email-noreply#somestuff.com
)
Splitting on something removes the delimiter (i.e. everything the regex matches). You probably want to split on
\s*<|>
instead. Or you can use preg_match with the regex
^(.*?)\s*<([^>]+)>
and use the first and second capturing groups.
This will do the job. click here for Codepad link
$header = '"email1#domain.com" <email1#domain.com>
News <news#e.domain.com>
Some Stuff <email-noreply#somestuff.com>';
$result = array();
preg_match_all('!(.*?)\s+<\s*(.*?)\s*>!', $header, $result);
$formatted = array();
for ($i=0; $i<count($result[0]); $i++) {
$formatted[] = array(
'name' => $result[1][$i],
'email' => $result[2][$i],
);
}
print_r($formatted);
preg_match_all("/<(.*?)>/", $string, $result_array);
print_r($result_array);
$email='"email1#domain.com" <email1#domain.com>
News <news#e.domain.com>
Some Stuff <email-noreply#somestuff.com>';
$pattern = '![^\>\<]+!';
preg_match_all($pattern, $email,$match);
print_r($match);
Ouput:
Array ( [0] => Array (
[0] => "email1#domain.com"
[1] => email1#domain.com
[2] => News
[3] => news#e.domain.com
[4] => Some Stuff
[5] => email-noreply#somestuff.com ) )
You can also split by <, and get rid of ">" in $result
$pattern = '/</';
$result = preg_split($pattern, $email);
$result = preg_replace("/>/", "", $result);