Can someone suggest a simple function that will parse a string into two parts, based on everything before and after the comma? I want to split up a latitude longitude pair so that I have two variables instead of one.
I need to turn this:
-79.5310706,43.6918950
into this:
-79.531070
43.6918950
$parts = explode(",", "-79.5310706,43.6918950");
echo $parts[0];
// -79.5310706
echo $parts[1];
// 43.69189506
Or if you need it to stay as a space-separated string, just str_replace() the comma to a space!
echo str_replace(",", " ", "-79.5310706,43.6918950");
// -79.531070 43.6918950
Related
I am new to php but learning fast. I am trying to extract the lowest price from a string of values like -
"12/6/2020:Some Text:345.44,13/6/2020:Some Text:375.88,14/6/2020:Some Text:275.81"
I need to get the value just before each comma and then get the lowest of these values. I know I can use min() if I get these values in a string. For the above example I need 275.81 (lowest).
Please see my code below. I am trying to explode the values and then put in a string. I dont think this is the best way by far and not having any luck. is there a better/cleaner way to do this?
$dates = explode(',', $resultx);
foreach($dates as $datew) {
$dater = explode(':', $datew);
echo $dater[2]. ",";
}
You can use regular expressions to extract the values, and then use min() to get the minimum value
<?php
$input = "2/6/2020:Some Text:345.44,13/6/2020:Some Text:375.88,14/6/2020:Some Text:275.81";
$pattern = '/(?:[^\:]+)\:(?:[^\:]+)\:(\d+\.\d+)\,*/';
if (preg_match_all($pattern, $input, $matches)) {
$minimumValue = min($matches[1]);
echo "minimum is: " . $minimumValue;
}
Here is a working example on 3v4l.org
In the pattern (?:[^\:]+) - equals any symbol, except the colon :
Section (\d+\.\d+) says that we need to capture the sequence containing two numbers with a dot . between them.
We look for two sections with any symbols, except :, and then capturing the third sections containing numbers, and everything ends with an optional comma ,
P.S. you could still get the result with your current approach
<?php
$input = "2/6/2020:Some Text:345.44,13/6/2020:Some Text:375.88,14/6/2020:Some Text:275.81";
$minimumValue = null;
$dates = explode(',', $input);
foreach($dates as $datew) {
$dater = explode(':', $datew);
$currentValue = floatval($dater[2]);
if (is_null($minimumValue) || $minimumValue > $currentValue) {
$minimumValue = $currentValue;
}
}
echo $minimumValue;
Here is a link to your approach on 3v4l.org
The problem is the following in PHP:
How to check if the input variables are numbers in an array if all of them was asked to separate with a " " (space) character within a form?
is_int and is_numeric don't work here, since it's a string not an array.
The answer might be easy, I'm just struggling with it in these late night hours.
The whole problem:
By using only one input field, read in numbers separated by " "(space), then print them out in ascending order. If there is any other variable besides numbers, print "error".
$str = "999 999 999 99";
$arr = explode(" ", $str);
foreach ($arr as $value) {
if(is_numeric($value)){
echo 'ok';
}
}
Might just replace the spaces:
if(is_numeric(str_replace(' ', '', $input)) {
// $input without spaces is numeric
}
I need to check if URL contains the term: "cidades".
For example:
http://localhost/site/cidades/sp/sorocaba
So, if positive, then I need to create two or three variables with the remaining content without the " / ", in this case:
$var1 = "sp";
$var2 = "sorocaba";
These variables will be cookies values in the beggining of the page, then, some sections will use as wp-query these values to filter.
This should work for you:
Here I check with preg_match() if the search word is in the url $str between two slashes. If yes I get the substr() from the url after the search word and explode() it into an array with a slash as delimiter. Then you can simply loop through the array an create the variables with complex (curly) syntax.
<?php
$str = "http://localhost/site/cidades/sp/sorocaba";
$search = "cidades";
if(preg_match("~/$search/~", $str, $m, PREG_OFFSET_CAPTURE)) {
$arr = explode("/", substr($str, $m[0][1]+strlen($m[0][0])));
foreach($arr as $k => $v)
${"var" . ($k+1)} = $v;
}
echo $var1 . "<br>";
echo $var2;
?>
output:
sp
sorocaba
Here are two functions that will do it for you:
function afterLast($haystack, $needle) {
return substr($haystack, strrpos($haystack, $needle)+strlen($needle));
}
And PHP's native explode.
First call afterLast, passing the /cidades/ string (or just cidades if you don't expect the slashes). Then take the result and explode on / to get your resulting array.
It would look like:
$remaining_string = afterLast('/cidades/', $url);
$items = explode('/', $remaining_string)
Just note that if you do not include the / marks with the afterLast call, your first element in the explode array will be empty.
I think this solution is better, since the resulting array will support any number of values, not just two.
This question already has answers here:
PHP: How can I explode a string by commas, but not wheres the commas are within quotes?
(2 answers)
Closed 8 years ago.
I'm trying to figure out how to add double quote between text which separates by a comma.
e.g. I have a string
$string = "starbucks, KFC, McDonalds";
I would like to convert it to
$string = '"starbucks", "KFC", "McDonalds"';
by passing $string to a function. Thanks!
EDIT: For some people who don't get it...
I ran this code
$result = mysql_query('SELECT * FROM test WHERE id= 1');
$result = mysql_fetch_array($result);
echo ' $result['testing']';
This returns the strings I mentioned above...
Firstly, make your string a proper string as what you've supplied isn't. (pointed out by that cutey Fred -ii-).
$string = 'starbucks, KFC, McDonalds';
$parts = explode(', ', $string);
As you can see the explode sets an array $parts with each name option. And the below foreach loops and adds your " around the names.
$d = array();
foreach ($parts as $name) {
$d[] = '"' . $name . '"';
}
$d Returns:
"starbucks", "KFC", "McDonalds"
probably not the quickest way of doing it, but does do as you requested.
As this.lau_ pointed out, its most definitely a duplicate.
And if you want a simple option, go with felipsmartins answer :-)
It should work like a charm:
$parts = split(', ', 'starbucks, KFC, McDonalds');
echo('"' . join('", "', $parts) . '"');
Note: As it has noticed in the comments (thanks, nodeffect), "split" function has been DEPRECATED as of PHP 5.3.0. Use "explode", instead.
Here is the basic function, without any checks (i.e. $arr should be an array in array_map and implode functions, $str should be a string, not an array in explode function):
function get_quoted_string($str) {
// Here you will get an array of words delimited by comma with space
$arr = explode (', ', $str);
// Wrapping each array element with quotes
$arr = array_map(function($x){ return '"'.$x.'"'; }, $arr);
// Returning string delimited by comma with space
return implode(', ', $arr);
}
Came in my mind a really nasty way to do it. explode() on comma, foreach value, value = '"' . $value . '"';, then run implode(), if you need it as a single value.
And you're sure that's not an array? Because that's weird.
But here's a way to do it, I suppose...
$string = "starbucks, KFC, McDonalds";
// Use str_replace to replace each comma with a comma surrounded by double-quotes.
// And then shove a double-quote on the beginning and end
// Remember to escape your double quotes...
$newstring = "\"".str_replace(", ", "\",\"", $string)."\"";
I have some text inside $content var, like this:
$content = $page_data->post_content;
I need to slice the content somehow and extract the sentences, inserting each one inside it's own var.
Something like this:
$sentence1 = 'first sentence of the text';
$sentence2 = 'second sentence of the text';
and so on...
How can I do this?
PS
I am thinking of something like this, but I need somekind of loop for each sentence:
$match = null;
preg_match('/(.*?[?\.!]{1,3})/', $content, $match);
$sentence1 = $match[1];
$sentence2 = $match[2];
Ty:)
Do you need them in variables? Can't you use a array?
$sentence = explode(". ", $page_data->post_content);
EDIT:
If you need variables:
$allSentence = explode(". ", $page_data->post_content);
foreach($allSentence as $key => $val)
{
${"sentence". $key} = $val;
}
Assuming each sentence ends with full stop, you can use explode:
$content = $page_data->post_content;
$sentences = explode('.', $content);
Now your sentences can be accessed like:
echo $sentences[0]; // 1st sentence
echo $sentences[1]; // 2nd sentence
echo $sentences[2]; // 3rd sentence
// and so on
Note that you can count total sentences using count or sizeof:
echo count($sentences);
It is not a good idea to create a new variable for each sentence, imagine you might have long piece of text which would require to create that number of variables there by increasing memory usage. You can simply use array index $sentences[0], $sentences[1] and so on.
Assuming a sentence is delimited by terminating punctuation, optionally followed by a space, you can do the following to get the sentences in an array.
$sentences = preg_split('/[!?\.]\s?/', $content);
You may want to trim any additional spaces as well with
$sentences = array_map('trim', $sentences);
This way, $sentences[0] is the first, $sentences[1] is the second and so on. If you need to loop through them you can use foreach:
foreach($sentences as $sentence) {
// Do something with $sentence...
}
Don't use individually named variables like $sentence1, $sentence2 etc. Use an array.
$sentences = explode('.', $page_data->post_content);
This gives you an array of the "sentences" in the variable $page_data->post_content, where "sentences" really means sequences of characters between full stops. This logic will get tripped up wherever a full stop is used to mean something other than the end of a sentence (e.g. "Mr. Watson").
Edit: Of course, you can use more sophisticated logic to detect sentence boundaries, as you have suggested. You should still use an array, not create an unknown number of variables with numbers on the ends of their names.