I have this "¶ms=&offer=art-by-jeremy-johnson" stored in my data base.
Is there any function / method to get the output as "Art by Jeremy Johnson" using the above as the input value. this should be changed to the output "Art by Jeremy Johnson" only on the runtime.
can this be done in PHP.
Please help.
$orig = '¶ms=&offer=art-by-jeremy-johnson';
$parts = explode('=', $orig);
$output = explode('-', end($parts));
echo ucwords(implode(' ', $output));
In Java, I guess you can just use lastIndexOf to get the last index of the equals sign, and get the remainder of the string (using substring).
if (myString.lastIndexOf("=") != -1) {
String words = myString.substring(myString.lastIndexOf("=")+1);
words.replaceAll("-", " ");
return words;
}
$string="¶ms=&offer=art-by-jeremy-johnson";
parse_str($string,$output);
//print_r($output);
$str=ucwords(str_replace("-"," ",$output['offer']));
If I understand well you want to not capitalized some words.
Here is a way to do it :
$str = "¶ms=&offer=art-by-jeremy-johnson";
// List of words to NOT capitalized
$keep_lower = array('by');
parse_str($str, $p);
$o = explode('-', $p['offer']);
$r = array();
foreach ($o as $w) {
if (!in_array($w, $keep_lower))
$w = ucfirst($w);
$r[] = $w;
}
$offer = implode(' ', $r);
echo $offer,"\n";
output:
Art by Jeremy Johnson
Related
I need replace ',' characters with regex in php, but only in odd positions
I have:
{"phone","11975365654","name","John Doe","cpf","42076792864"}
I want replace ',' to ':', but only the odd:
{"phone":"11975365654","name":"John Doe","cpf":"42076792864"}
I'm trying this regex:
preg_replace('/,/', ':', $data)
But it get all quotes and no only the odd.
Can you help me?
Make it simple:
preg_replace('/(("[a-z]+"),(".+?"))+/', '$2:$3', $a)
Rather than regex, this just converts the list to an array (using str_getcsv() to cope with the quotes). Then loops every other item in the list, using that item as the key and the next item as the value. This can then be json_encoded() to give the result...
$data = str_getcsv(trim($input, "{}"));
$output = [];
for ( $i=0, $k=count($data); $i < $k; $i+=2) {
$output[$data[$i]] = $data[$i+1];
}
echo json_encode($output);
It is not ideal to use regex for this task. Having said that, if you know that your input can be matched by a simple regex, this should do it :
$str = '{"phone","11975365654","name","John Doe","cpf","42076792864"}';
$result = preg_replace('/,(.*?(?:,|[^,]*$))/ms', ':\\1', $str);
This lenient to some extra characters but it will fail if any string contains commas
Example
Here's an example of using standard PHP functions:
$input = '{"phone","11975365654","name","John Doe","cpf","42076792864"}';
$dataIn = str_getcsv(trim($input, '{}'));
$keys = array_filter($dataIn, function ($key) { return !($key & 1); }, ARRAY_FILTER_USE_KEY);
$values = array_filter($dataIn, function ($key) { return $key & 1; }, ARRAY_FILTER_USE_KEY);
$DataOut = array_combine($keys, $values);
$output = json_encode($DataOut);
echo $output;
This code is a lot longer than using a regex, but it is probably easier to read and maintain in the long run. It can cope with commas in the values.
Another option could be using array_splice and loop while there are still elements in the array:
$str = '{"phone","11975365654","name","John Doe","cpf","42076792864"}';
$data = str_getcsv(trim($str, '{}'));
$result = array();
while(count($data)) {
list($k, $v) = array_splice($data, 0, 2);
$result[$k] = $v;
}
echo json_encode($result);
Output
{"phone":"11975365654","name":"John Doe","cpf":"42076792864"}
I have a long string variable that contains coordinates
I want to keep each coordinate in a separate cell in the array according to Lat and Lon..
For example. The following string:
string = "(33.110029967689556, 35.60865999564635), (33.093492845160036, 35.63955904349791), (33.0916232355565, 35.602995170206896)";
I want this:
arrayX[0] = "33.110029967689556";
arrayX[1] = "33.093492845160036";
arrayX[2] = "33.0916232355565";
arrayY[0] = "35.60865999564635";
arrayY[1] = "35.63955904349791";
arrayY[2] = "35.602995170206896";
Does anyone have an idea ?
Thanks
Use substr to modify sub string, it allow you to do that with a little line of code.
$array_temp = explode('),', $string);
$arrayX = [];
$arrayY = [];
foreach($array_temp as $at)
{
$at = substr($at, 1);
list($arrayX[], $arrayY[]) = explode(',', $at);
}
print_r($arrayX);
print_r($arrayY);
The simplest way is probably to use a regex to match each tuple:
Each number is a combination of digits and .: the regex [\d\.]+ matches that;
Each coordinate has the following format: (, number, ,, space, number,). The regex is \([\d\.]+,\s*[\d\.]+\).
Then you can capture each number by using parenthesis: \(([\d\.]+),\s*([\d\.]+)\). This will produce to capturing groups: the first will contain the X coordinate and the second the Y.
This regex can be used with the method preg_match_all.
<?php
$string = '(33.110029967689556, 35.60865999564635), (33.093492845160036, 35.63955904349791), (33.0916232355565, 35.602995170206896)';
preg_match_all('/\(([\d\.]+)\s*,\s*([\d\.]+)\)/', $string, $matches);
$arrayX = $matches['1'];
$arrayY = $matches['2'];
var_dump($arrayX);
var_dump($arrayY);
For a live example see http://sandbox.onlinephpfunctions.com/code/082e8454486dc568a6557058fef68d6f10c8dbd0
My suggestion, working example here: https://3v4l.org/W99Uu
$string = "(33.110029967689556, 35.60865999564635), (33.093492845160036, 35.63955904349791), (33.0916232355565, 35.602995170206896)";
// Split by each X/Y pair
$array = explode("), ", $string);
// Init result arrays
$arrayX = array();
$arrayY = array();
foreach($array as $pair) {
// Remove parentheses
$pair = str_replace('(', '', $pair);
$pair = str_replace(')', '', $pair);
// Split into two strings
$arrPair = explode(", ", $pair);
// Add the strings to the result arrays
$arrayX[] = $arrPair[0];
$arrayY[] = $arrPair[1];
}
You need first to split the string into an array. Then you clean the value to get only the numbers. Finally, you put the new value into the new array.
<?php
$string = "(33.110029967689556, 35.60865999564635), (33.093492845160036, 35.63955904349791), (33.0916232355565, 35.602995170206896)";
$loca = explode(", ", $string);
$arr_x = array();
$arr_y = array();
$i = 1;
foreach($loca as $index => $value){
$i++;
if ($i % 2 == 0) {
$arr_x[] = preg_replace('/[^0-9.]/', '', $value);
}else{
$arr_y[] = preg_replace('/[^0-9.]/', '', $value);
}
}
print_r($arr_x);
print_r($arr_y);
You can test it here :
http://sandbox.onlinephpfunctions.com/code/4bf04e7aabeba15ecfa114d8951eb771610a43a4
How to merge two words together letter by letter in php on the following way:
Input #1: Apricot
Input #2: Kiwi
Expected output: AKpirwiicot.
So that if one word's characters are more than the other, it simply writes it down until the end.
I tried it by this logic:
Input smthing
str_split()
array_merge()
But I failed. Any solutions appreciated.
$string1 and $string2 can be in any order.
$string1=str_split("Apricot");
$string2=str_split("Kiwi");
if(count($string2)>count($string1)){
$templ = $string1;
$string1 = $string2;
$string2 = $temp;
}
$result = "";
foreach($string1 as $key => $var){
{
$result.=$var;
if(isset($string2[$key])){
$result.$string2[$key];
}
}
echo $result;
Array_merge() also sticks one array on the end of the other so it wouldn't do what you are looking for I believe.
edit : ive adjusted to take into account no order, like #nikkis answer.
How about this:
def str_merge(a, b):
s = ''
k = min(len(a), len(b))
for i in range(k):
s += a[i] + b[i]
s += a[k:] + b[k:]
return s
In PHP:
function merge($a, $b)
{
$s = '';
$k = min(strlen($a), strlen($b));
for($i=0; $i<$k; $i++)
{
$s = $s . $a[$i] . $b[$i];
}
$s = $s . substr($a, $k) . substr($b, $k);
}
Please forgive my PHP, not my strongest language...
My problem is not very complex but I can't find a solution yet. I have a string:
$temp_string = '20938999038,0.5,83888999289,0.5,98883888778,0.9';
// Meaning syskey, price, syskey, price, syskey, price
I want to remove price and show only syskey.
My desirable result:
'20938999038,83888999289,98883888778'
Thanks in advance.
You can explode it by delimiter
$explode = explode(",", $temp_string);
unset($explode[1], $explode[3], $explode[5]);
Assuming your string always follows this pattern.
You can try:
$string = "20938999038,0.5,83888999289,0.5,98883888778,0.9";
$new = array();
foreach(explode(",", $string) as $k => $v) {
$k % 2 or $new[] = $v;
}
echo implode(",", $new); // 20938999038,83888999289,98883888778
is there a way to slice a string lets say i have this variable
$output=Country=UNITED STATES (US) &City=Scottsdale, AZ &Latitude=33.686 &Longitude=-111.87
i want to slice it in a way i want to pull latitude and longitude values in to seperate variables, subtok is not serving the purpose
You don't need a regular expression for this; use explode() to split up the string, first by &, and then by =, which you can use to effectively parse it into a nice little array mapping names to values.
$output='Country=UNITED STATES (US) &City=Scottsdale, AZ &Latitude=33.686 &Longitude=-111.87';
parse_str($output, $array);
$latitude = $array['latitude'];
You could also just do
parse_str($output);
echo $latitude;
I think using an array is better as you are not creating variables all over the place, which could potentially be dangerous (like register_globals) if you don't trust the input string.
It looks likes it's coming from an URL, although the URL encoding is gone.
I second the suggestions of using explode() or preg_split() but you might also be interested in parse_str().
$output = "City=Scottsdale, AZ &Latitude=33.686 &Longitude=-111.87";
parse_str($output, $results);
$lat = $results['Latitude'];
$lon = $results['Longitude'];
I'm not sure exactly what you're demonstrating in your code, maybe it's just some typos, is the "$output" the name of the variable, or part of the string?
Assuming it's the name of the variable, and you just forgot to put the quotes on the string, you have a couple options:
$sliced = explode('&', $output)
This will create an array with values: "Country=UNITED STATES(US) ", "City=Scottsdale, AZ ", etc.
$sliced = preg_split('/[&=]/', $output);
This will create an array with alternating elements being the "variables" and their values: "Country", "UNITED STATES(US) ", "City", "Scottsdale, AZ ", etc.
You could do the following:
$output = 'Country=UNITED STATES (US) &City=Scottsdale, AZ &Latitude=33.686 &Longitude=-111.87';
$strs = explode('&', $output);
foreach ($strs as $str) {
list($var, $val) = explode('=',$str);
$$var = trim($val);
}
This would give you variables such as $Latitude and $Longitude that are set to the value in the key/value pair.
All of the other Answers are Insufficient. This Should Work Every Time!
function slice($string, $start){
$st = $string; $s = $start; $l = strlen($st); $a = func_get_args();
$e = isset($a[2]) ? $a[2] : $l;
$f = $e-$s;
$p = $e < 0 && $s > 0 ? $l+$f : $f;
return substr($st, $s, $p);
}
I suggest you read about regular expressions in the PHP help.