Php explode string only if the string contains '.' - php

I have this explode (with list):
$dm = "blablabla.ff";
list($d, $l) = explode('.', $dm, 2);
Now, i want the explode will cut the string only if the string contains .
because the list will return error if the string not contains ., error like this: Undefined offset: 1.
How can i do this short way?

$dm = "blablabla.ff";
if(strpos($dm,".") !== false){
list($d, $l) = explode('.', $dm, 2);
}

If you explode $dm = "blablabla.ff"; you get two arrays.
one for $d and one for $l.
$d = 'blablabla';
$l = 'ff';
If you explode $dm = "blablablaff"; you get one array.
One for $d and no one for $l.
$d = 'blablablaff';
$l = null;
Now if you have no arrays to fill the list ($l) it will error.

You could try this:
<?php
$dm = "blablabla.ff";
$d = null;
$l = null;
if( stristr($dm, ".")){
list($d, $l) = explode('.', $dm, 2);
}
var_dump($d, $l);

Related

Find the two longest strings separated by dash in PHP

I want to define two new variables as the longest strings from a given string. if the string does not contain any dashes, just choose it for both.
Example:
$orig=`welcome-to-your-world`
$s1=`welcome`
$s2=`world`
$orig=`welcome-to-your-holiday`
$s1=`welcome` // order not important
$s2=`holiday`// order not important
$orig=`welcome`
$s1=`welcome`
$s2=`welcome`
Solution with explode and sorting result array by length of words:
$orig = 'welcome-to-your-world';
$parts = explode('-', $orig);
if (1 < count($parts)) {
usort($parts, function($a, $b) { return strlen($a) < strlen($b); });
$s1 = array_shift($parts);
$s2 = array_shift($parts);
} else {
$s1 = $s2 = $orig;
}
echo $s1 . PHP_EOL . $s2;
Fiddle here.
It seems like your string is in dash-case (words in lower case separated by dashes).
So, you can do the following:
// convert origin in an array
$origin_array = explode("-", $origin);
//retrivies the first element from array
$s1 = '';
$s2 = '';
// get the longest string
foreach($origin_array as $word) {
if(strlen($word) > strlen($s1)) {
$s1 = $word;
}
}
// remove the longest word from the array
$origin_array = array_diff($origin_array, [$s1]);
// get the second longest string
foreach($origin_array as $word) {
if(strlen($word) > strlen($s2)) {
$s2 = $word;
}
}
I think that solves your problem. Hope that helps!
Note: This method is not efficient because it runs foreach twice. The other answer is better if you care about performance.
$orig = 'welcome-to-your-world';
$array = explode('-', $orig);
$lengths = array_map('strlen', $array);
$s1key = array_search(max($lengths), $lengths);
$s1 = $array[$s1key];
unset ($array[$s1key], $lengths[$s1key]);
$s2key = array_search(max($lengths), $lengths);
$s2 = $array[$s2key];

Dynamic explosion with specific character

I am trying to extract a string in php and convert them to comma separated strings
Here are some sample string I am working with and the results I need:
input :
G1_C2_S3_T5 or G4_C5_S4_T7_I6_H3
Result must be :
G1,G1_C2,G1_C2_S3,G1_C2_S3_T5
or
G4,G4_C5,G4_C5_S4,G4_C5_S4_T7,G4_C5_S4_T7_I6,G4_C5_S4_T7_I6_H3
Input length can be dynamic for comma separation
Is this correct :
$arr = explode("_", $string, 2);
$first = $arr[0];
How can i do that in php?
Something like this should work, $string is the string you are working with
//explode by underscore
$parts = explode('_', $string);
$c = [];
//do until nothing else to pop from array
while (!empty($parts)) {
$c[] = implode('_', $parts);
//will pop element from end of array
array_pop($parts);
}
//reverse
$c = array_reverse($c);
//glue it with comma
echo implode(',', $c);
You should notice that the number of underscore-separated values in your initial string e.g. G4_C5_S4_T7_I6_H3 (6) is equal to the number of comma-separated values in your desired string e.g. G4,G4_C5,G4_C5_S4,G4_C5_S4_T7,G4_C5_S4_T7_I6,G4_C5_S4_T7_I6_H3 (6). So we'll use this number in our first loop $end = count($parts).
$str = "G4_C5_S4_T7_I6_H3";
$newstr = '';
$parts = explode('_', $str);
$comma = '';
for ($i = 0, $end = count($parts); $i < $end; $i++) {
$newstr .= $comma;
$underscore = '';
// build underscore-separated value
// index i is used to indicate up which value to stop at for each iteration
for ($j = 0; $j <= $i; $j++) {
$newstr .= $underscore . $parts[$j];
// set underscore after the first iteration of the loop
$underscore = '_';
}
// set comma after the first iteration of the loop
$comma = ',';
}
echo $newstr; // G4,G4_C5,G4_C5_S4,G4_C5_S4_T7,G4_C5_S4_T7_I6,G4_C5_S4_T7_I6_H3
The explosion is easy:
$parts = explode('_', $string);
Now you get a $parts array like [ 'G1', 'C2', 'S3', 'T5' ].
You want to convert this to an array so that each item is the concatenation of that item and every other item before it:
$prev = [ ];
array_walk(
$parts,
function(&$value) use (&$prev) {
$prev[] = $value;
$value = implode('_', $prev);
}
);
Now $parts holds the elements:
print implode(', ', $parts);
yields
G1, G1_C2, G1_C2_S3, G1_C2_S3_T5

PHP - Get integer after word inside string

Having this URL string:
$URL = "www.example.com/search/brand/model/priceRange:2000-5000/year:1994-2015";
How can I identify the price range and the year? So that my final variables result in this:
$price_from = 2000;
$price_until= 5000;
$year_from = 1994;
$year_until= 2015;
After reading a few posts I've tought of using the explode() method but I'm not sure how to do it having a string like this, thanks in advance
EDIT:
I forgot to mention that the order of the elements in the URL can change, thank you
You could try something like this:
$result = array();
$url_parts = explode('/', $URL);
foreach ($url_parts as $part) {
if (strpos($part, ':') && strpos($part, '-')) {
$sub = explode(':', $part);
$range = explode('-', $sub[1]);
$result[$sub[0].'_from'] = $range[0];
$result[$sub[0].'_until'] = $range[1];
}
}
demo

Need to remove everything that is after a letter with PHP

I have this link: http://www.youtube.com/e/fIL7Nnlw1LI&feature=related
I need a way in PHP to completely remove everything that is after EACH & in the link.
So it will become : http://www.youtube.com/watch?v=fIL7Nnlw1LI
Attention it could have more than one &
Everything after EACH &, & included, must be deleted from the string
How can I do it in PHP?
You can do this ::
$var = "http://www.youtube.com/e/fIL7Nnlw1LI&feature=related";
$url = explode("&", $var);
$url = $url[0]; //URL is now what you want, the part before First "&"
As I wrote in rpevious your question you can use this 1-line script:
$str = strtok($str,'&');
You can combine strpos with substr:
$spos = strpos($s, "&");
$initial_string = $spos ? substr($s, 0, $spos) : $s;
$url = "http://www.youtube.com/e/fIL7Nnlw1LI&feature=related";
$ampPos = strpos($var, '&');
if ($ampPos !== false)
{
$url = substr($url, 0, $ampPos);
}
Don't use explode, regexp or any other greedy algorithm, it's a waste of resources.
EDIT (Added performance information):
In the preg_match documentation: http://www.php.net/manual/en/function.preg-match.php
Tested explode myself with the following code:
$url = "http://www.youtube.com/e/fIL7Nnlw1LI&feature=related&bla=foo&test=bar";
$time1 = microtime(true);
for ($i = 0; $i < 1000000; $i++)
{
explode("&", $url);
$url = $url[0];
}
$time2 = microtime(true);
echo ($time2 - $time1) . "\n";
$time1 = microtime(true);
for ($i = 0; $i < 1000000; $i++)
{
$ampPos = strpos($url, "&");
if ($ampPos !== false)
$url = substr($url, 0, $ampPos);
}
$time2 = microtime(true);
echo ($time2 - $time1) . "\n";
Gave the following result:
2.47602891922
2.0289251804352
Look at the strpos function, that will give you where the first occurance of a character - in your case & is in a string. From that you can use substr to retrieve the piece of the string you want.
You can use the explode function () to split the string. $url = explode ( "&", $needle ) and then get the first array element.

Modify numbers inside a string PHP

I have a string like this:
$string = "1,4|2,64|3,0|4,18|";
Which is the easiest way to access a number after a comma?
For example, if I have:
$whichOne = 2;
If whichOne is equal to 2, then I want to put 64 in a string, and add a number to it, and then put it back again where it belongs (next to 2,)
Hope you understand!
genesis'es answer with modification
$search_for = 2;
$pairs = explode("|", $string);
foreach ($pairs as $index=>$pair)
{
$numbers = explode(',',$pair);
if ($numbers[0] == $search_for){
//do whatever you want here
//for example:
$numbers[1] += 100; // 100 + 64 = 164
$pairs[index] = implode(',',$numbers); //push them back
break;
}
}
$new_string = implode('|',$pairs);
$numbers = explode("|", $string);
foreach ($numbers as $number)
{
$int[] = intval($number);
}
print_r($int);
$string = "1,4|2,64|3,0|4,18|";
$coordinates = explode('|', $string);
foreach ($coordinates as $v) {
if ($v) {
$ex = explode(',', $v);
$values[$ex[0]] = $ex[1];
}
}
To find the value of say, 2, you can use $whichOne = $values[2];, which is 64
I think it is much better to use the foreach like everyone else has suggested, but you could do it like the below:
$string = "1,4|2,64|3,0|4,18|";
$whichOne = "2";
echo "Starting String: $string <br>";
$pos = strpos($string, $whichOne);
//Accomodates for the number 2 and the comma
$valuepos = substr($string, $pos + 2);
$tempstring = explode("|", $valuepos);
$value = $tempstring[0]; //This will ow be 64
$newValue = $value + 18;
//Ensures you only replace the index of 2, not any other values of 64
$replaceValue = "|".$whichOne.",".$value;
$newValue = "|".$whichOne.",".$newValue;
$string = str_replace($replaceValue, $newValue, $string);
echo "Ending String: $string";
This results in:
Starting String: 1,4|2,64|3,0|4,18|
Ending String: 1,4|2,82|3,0|4,18|
You could run into issues if there is more than one index of 2... this will only work with the first instance of 2.
Hope this helps!
I know this question is already answered, but I did one-line solution (and maybe it's faster, too):
$string = "1,4|2,64|3,0|4,18|";
$whichOne = 2;
$increment = 100;
echo preg_replace("/({$whichOne},)(\d+)/e", "'\\1'.(\\2+$increment)", $string);
Example run in a console:
noice-macbook:~/temp% php 6642400.php
1,4|2,164|3,0|4,18|
See http://us.php.net/manual/en/function.preg-replace.php

Categories