PHP - Get integer after word inside string - php

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

Related

php need assistance with regular expression

I want to parse and expand the given strings in PHP.
From
0605052&&-5&-7&-8
0605052&&-4&-7
0605050&&-2&-4&-6&-8
To
0605052, 0605053 ,0605054 ,0605055, 0605057, 0605058
0605052,0605053,0605054,0605057
0605050,0605051,0605052,0605054,0605056,0605058
can someone help me with that? thanks in advance!
Your question is not very clear, but I think you mean a solution like this:
Edited: Now the hole ranges were shown and not only the specified numbers.
<?php
$string = "0605052&&-5&-7&-8";
$test = '/^([0-9]+)\&+/';
preg_match($test, $string, $res);
if (isset($res[1]))
{
$nr = $res[1];
$test = '/\&\-([0-9])/';
preg_match_all($test, $string, $res);
$result[] = $nr;
$nrPart = substr($nr, 0, -1);
$firstPart = substr($nr, -1);
if (isset($res[1]))
{
foreach ($res[1] as &$value)
{
if ($firstPart !== false)
{
for ($i=$firstPart+1; $i<=$value; $i++)
{
$nr = $nrPart . $i;
$result[] = $nr;
}
$firstPart = false;
}
else
{
$nr = $nrPart . $value;
$result[] = $nr;
$firstPart = $value;
}
}
}
var_dump($result);
}
?>
This delivers:
result[0] = "0605052"
result[1] = "0605053"
result[2] = "0605054"
result[3] = "0605055"
result[4] = "0605057"
result[5] = "0605058"
I think a multi step approach is the best thing to do here.
E.g. take this as an example 0605052&&-5&-7&-8:
Split at -. The result will be 0605052&&, 5&, 7&, 8
The first result 0605052&& will help you create your base. Simply substring the numbers by finding first occurence of & and substring to the next to last number. Result will be 060505. You will also need the last number, so get it as well (which is 2 in this case).
Get the remaining ends now, all \d& are simple to get, simply take the first character of the string (or if those can be more than one number, use substring with first occurence of & approach again).
The last number is simple: it is 8.
Now you got all important values. You can generate your result:
The last number from 2., all numbers from 3. and the number from 4. together with your base are the first part. In addition, you need to generate all numbers from the last number of 2. and the first result of 3. in a loop by a step of 1 and append it to your base.
Example Code:
<?php
$str = '0605052&&-5&-7&-8';
$split = explode('-', $str);
$firstAmpBase = strpos($split[0], '&');
$base = substr($split[0], 0, $firstAmpBase - 1);
$firstEnd = substr($split[0], $firstAmpBase - 1, 1);
$ends = [];
$firstSingleNumber = substr($split[1], 0, strpos($split[1], '&'));
for ($i = $firstEnd; $i < $firstSingleNumber; $i++) {
array_push($ends, $i);
}
array_push($ends, $firstSingleNumber);
for ($i = 2; $i < count($split) - 1; $i++) {
array_push($ends, substr($split[$i], 0, strpos($split[$i], '&')));
}
array_push($ends, $split[count($split) - 1]);
foreach ($ends as $end) {
echo $base . $end . '<br>';
}
?>
Output:
0605052
0605053
0605054
0605055
0605057
0605058

Php explode string only if the string contains '.'

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);

PHP - Create Arrays from Strings in another Array

I've spent a long time on this problem, and I cannot for the life of me figure it out. Any help will be much appreciated!
I have an array of strings, which I am using to get information from, i.e. the month of an event is hidden within the url (the string), and I want to cycle through all the urls and get the month, and other data out and make each data-piece it's own array.
Here's the deal, I can do it twice successfully, but the third time I try to create an array, it breaks down.
This code works:
$months = array();
$times = array();
foreach ($ticketsLinks as $ticketsLink){
//CREATE VENUE ARRAY
// Delete all the way up to "-tickets-"
$findMeA = '-tickets-';
$posA = strpos($ticketsLink, $findMeA);
$posA = $posA + 9;
$venue = substr($ticketsLink, $posA);
// Find the first number in the string - delete everything after that.
$lengthA = strlen($venue);
$parts = str_split($venue);
$first_num = -1;
$num_loc = 0;
foreach ($parts AS $a_char) {
if (is_numeric($a_char)) {
$first_num = $num_loc;
break;
}
$num_loc++;
}
$posB = -$lengthA + $num_loc - 1;
$venue = substr($venue, 0, $posB);
// Replace dashes with spaces.
$venue = str_replace("-"," ",$venue);
//Add value to venue's array
$venues[] = $venue;
// CREATE TIME ARRAY
$pos = strrpos($ticketsLink, '-');
$pos = strlen($ticketsLink) - $pos - 1;
$time = substr($ticketsLink, -$pos);
$pos = strpos($time, '/');
$time = substr($time, 0, $pos);
$times[] = $time;
}
This code does not:
$months = array();
$times = array();
$years = array();
foreach ($ticketsLinks as $ticketsLink){
//CREATE VENUE ARRAY
// Delete all the way up to "-tickets-"
$findMeA = '-tickets-';
$posA = strpos($ticketsLink, $findMeA);
$posA = $posA + 9;
$venue = substr($ticketsLink, $posA);
// Find the first number in the string - delete everything after that.
$lengthA = strlen($venue);
$parts = str_split($venue);
$first_num = -1;
$num_loc = 0;
foreach ($parts AS $a_char) {
if (is_numeric($a_char)) {
$first_num = $num_loc;
break;
}
$num_loc++;
}
$posB = -$lengthA + $num_loc - 1;
$venue = substr($venue, 0, $posB);
// Replace dashes with spaces.
$venue = str_replace("-"," ",$venue);
//Add value to venue's array
$venues[] = $venue;
// CREATE TIME ARRAY
$pos = strrpos($ticketsLink, '-');
$pos = strlen($ticketsLink) - $pos - 1;
$time = substr($ticketsLink, -$pos);
$pos = strpos($time, '/');
$time = substr($time, 0, $pos);
$times[] = $time;
// CREATE YEAR ARRAY
$pos = strrpos($ticketsLink, '-');
$pos = strlen($ticketsLink) - $pos - 1;
$year = substr($ticketsLink, -$pos);
$pos = strpos($year, '/');
$year = substr($year, 0, $pos);
$years[] = $year;
}
For the purposes of this example, I kept the code to get the year string and the time string exactly the same to show that that wasn't the problem. I've gone through the above code and tried to debug it - the only thing that's making it not work is when I push the year variable to the years array.
--- UPDATED TO INCLUDE NEW INFORMATION -----
Unfortunately, breaking apart the URL to get the requisite information is the best way to do this - the URLs are coming from a CSV feed.
So, after the first foreach, then just for a test, I run a foreach loop through the $years array -
foreach($years as $year){
echo $year;
}
Eventually, the $years array will be passed to a mySQL database, but for now, I just want to make sure I'm processing the URL correctly. The resultant loop should look something like this:
2014
2015
2014
2016
Instead, I get nothing, and all the code after the first foreach (where I'm breaking down the URL), doesn't run. I have an echo at the bottom that echos "This code works!", and it doesn't print to the screen when I try to push values to the $years array.

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