Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
When i read an array i got value set like this "lat" : -37.8087928,. I want to only -37.8087928 part. what is the correct way to do that.
I did it in this way:
$value = '"lat" : -37.8087928,';
$ex = explode(':', $value);
and
$ex2 = explode(',', $ex[1]);
final resualt $ex2[0]
is this correct or what is the correct way, thank you all
$value = '"lat" : -37.8087928,';
$final_value = preg_replace("/[^0-9.\-]/", "", $value);
The code above will strip all characters that are not numeric, dot or hyphen.
You can delete all spaces in a string
$stingname=" test manish ";
str_replace(" ","",$stingname);
echo $stingname;
Result
testmanish
that's object notation. you might want to try
$locations = json_decode($value)
then you could access it like this:
echo $locations->lat; // prints -37.8087928
if you don't want to do that you could do:
$locationArray = explode($value, ':'); // returns [0: 'lat', 1: -37.8087928]
echo trim($locationArray[1]); // prints -37.8087928. trim to get rid of whitespace
The correct method depends on the variability of the input string - "like this" is not an adequate explanation.
Your parser suffices - but has no error handling, nor any means of dealing with a differently formatted string. Using a regexp as described by jorge is more robust, however may not cope with some input scenarios.
The input string you provided looks very like JSON - in which case you should be using a JSON parser - PHP has a very good one built in - which will simply reject non-conformant input.
There is no problem in your approach. But you can use also this which is more easy to understand:
$value = '"lat" : -37.8087928,';
echo $float = filter_var($value, FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
Hope this help you!
you can read more about it here
People are suggesting regex's and explodes, why? Thats slow and not needed. If you have a fixed string, you can do it with some string functions:
$value = '"lat" : -37.8087928,';
$result = trim( substr($value, strpos($value,":")+1) ), " ,");
This works by finding the : in that string and substract it till the end. Then with a trim you remove the spaces and the comma. If the comma is ALWAYS there, you can do this, and drop the trim:
$result = substr($value, strpos($value,":")+1), -1 );// till -1 from the end
Related
This question already has answers here:
implode() string, but also append the glue at the end
(6 answers)
Closed 1 year ago.
I have this sentence:
piece:5,dozen:10
and I need to print it via php like this:
piece:5$,dozen:10$
without editing the line in the editor, I need php to do it automatically. Now I thought to split it like this:
$uom = "piece:5,dozen:10";
$lst1 = explode(',', $uom);
var_dump($lst1);
and it returned like this:
array (size=2)
0 => string 'piece:5' (length=7)
1 => string 'dozen:10' (length=8)
which is ok for now, so I need after each string piece:5$ dozen:10$ and then I did this:
$lst2 = implode('$ ', $lst1);
echo $lst2;
It printed:
piece:5$ dozen:10
I need the $ to be printed also after 10, so it will be like this:
piece:5$ dozen:10$
What is the right way to do this? What did I do wrong? What if the values are dynamically coming from the database?
You can use a combination of explode, array_map and implode like so:
<?php
$uom = 'piece:5,dozen:10';
$add_dollars = array_map(function($e) {
return $e . '$';
}, explode(',', $uom));
echo implode(" ", $add_dollars);
I see few explode-implode answers. I don't want to duplicate answer, so let me do it another way – with regex.
$data = "piece:5,dozen:10";
echo preg_replace("/(\d+)/i", "$1\$", $data);
It may be a good idea to make it a bit more complex, i.e. take not only \d+, but also previous string and colon. Rather without(!) comma. In my opinion this may be better (because it's usually worth to be strict in regex):
$data = "piece:5,dozen:10";
echo preg_replace("/([a-zA-Z]:\d+)/i", "$1\$", $data);
I encourage you to read php manual: preg_replace.
Answering also the question about jQuery – you don't need to use jQuery, you can do that in pure javascript. And it will be really similar! For example:
let data = "piece:5,dozen:10";
let modified = data.replace(/([a-zAZ]:\d+)/g,"$1\$");
console.log(modified);
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
Here is my string. The total json response comes as a String. Task is to identify the words after subdomain and comment.
{item_type:a,custom_domain:"google.com",subdomain:analytics,duration:324.33, id:2892928, comment:goahead,domain_verified:yes}, {item_type:b,custom_domain:"yahoo.com",subdomain:news,comment:awesome,domain_verified:no}, {item_type:c,custom_domain:"amazon.com",subdomain:aws,width:221,image_id:3233,height:13, comment:keep it up,domain_verified:no}, {item_type:d,custom_domain:"facebook.com",subdomain:m,slug:sure,domain_verified:yes}
The output should be like,
analytics, goahead
news, awesome
aws, keep it up
m, sure
To put it simply, I need words starting with ^subdomain: and ends with a comma and then words starting with ^comment: and ends with a comma.
The incoming string contains huge amount of data. Each and every string will contains thousands of subdomain and comments. I've tried with preg_match_all method. But I didn't get the proper way to do it.
I see 3 ways (I'm not sure about which one has the best perfs, but I will bet on the last procedural way):
Using the json_decode function, you will get an array from your string and then just iterate over it to get your data
Using regexp, see an example here with pattern /subdomain:(.*?),.*?comment:(.*?),/
Using a procedural function, like :
$subdomains = [];
$comments = [];
$subdomainLen = strlen('subdomain:');
$commentLen = strlen('comment:');
$str = '{item_type:a,custom_domain:"google.com",subdomain:analytics,duration:324.33, id:2892928, comment:goahead,domain_verified:yes}, {item_type:b,custom_domain:"yahoo.com",subdomain:news,comment:awesome,domain_verified:no}, {item_type:c,custom_domain:"amazon.com",subdomain:aws,width:221,image_id:3233,height:13, comment:keep it up,domain_verified:no}, {item_type:d,custom_domain:"facebook.com",subdomain:m,slug:sure,domain_verified:yes}';
// While we found the 'subdomain' pattern
while(($subdomainPos = strpos($str, 'subdomain')))
{
// Removes all char that are behind 'subdomain'
$str = substr($str, $subdomainPos + $subdomainLen);
// Retrieves the subdomain str and push to array
$subdomains[] = substr($str, 0, strpos($str, ','));
// If pattern 'comment' exists, do the same as before to extract the comment
if($commentPos = strpos($str, 'comment'))
{
$str = substr($str, $commentPos + $commentLen);
$comments[] = substr($str, 0, strpos($str, ','));
}
}
Giving you string example you can use the following regex, to capture all the subdomains:
/(subdomain:)[\w|\s]+,/gm
And:
/(comment:)[\w|\s]+,/gm
To capture comments.
Here's a working example for subdomains.
If just want the content of the subdomain or comment you can then remove them from the match results.
Try this code... Here is LIVE EXAMPLE
<?php
$string ='{item_type:a,custom_domain:"google.com",subdomain:analytics,duration:324.33, id:2892928, comment:goahead,domain_verified:yes}, {item_type:b,custom_domain:"yahoo.com",subdomain:news,comment:awesome,domain_verified:no}, {item_type:c,custom_domain:"amazon.com",subdomain:aws,width:221,image_id:3233,height:13, comment:keep it up,domain_verified:no}, {item_type:d,custom_domain:"facebook.com",subdomain:m,slug:sure,domain_verified:yes}';
$v1= explode(',',str_replace("}","",str_replace("{","",$string)));
$result =array();
foreach($v1 as $key=>$val)
{
$v2 = explode(':',$val);
if(trim($v2[0])=='subdomain' || trim($v2[0])=='comment')
{
$result[]= $v2[1];
}
}
echo implode(',',$result);
?>
This will output :
analytics,goahead,news,awesome,aws,keep it up,m
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have a PHP variable which contains numbers separated by a space. I want to replace each space with a new line and then want to put those numbers into a list or HTML table.
Here's an example string:
$numbers = "9844786187 9844786187 9864097002 9864097002 9590951428 9590951428 9839014611 9839014611 9039771174 9039771174";
These numbers are dynamic and there could be more or less numbers.
How can I achieve my output?
As suggested, you can use str_replace():
$numbers = str_replace(' ', '\n', $numbers);
preg_replace is a "super" str_replace(), usign regex, you can use it the same way
$numbers = preg_replace('/ /', '\n', $numbers);
Those / are delimiters. In your case, regex are useless. You should use str_replace.
And as Daryll Gill suggested, using :
$numbers = str_replace(' ', '<br>', $numbers);
Will give better result for web printing. You can use nl2br() function on numbers on printing to get the same result with the first replacing proposal
I (think I) clarified your question and believe you're attempting to take a list of numbers in a string, separated by spaces, and output it in different ways (eg, list or table). The approach you asked us to use doesn't sound like the best for this. Instead, I would suggest explode():
$numbers = "9844786187 9844786187 9864097002 9864097002 9590951428 9590951428 9839014611 9839014611 9039771174 9039771174";
$number_array = explode(" ", $numbers);
echo "<ul>\n";
foreach($number_array as $number){
echo "\t<li>$number</li>\n";
}
echo "</ul>\n"
Output:
<ul>
<li>9844786187</li>
<li>9844786187</li>
<li>9864097002</li>
<li>9864097002</li>
<li>9590951428</li>
<li>9590951428</li>
<li>9839014611</li>
<li>9839014611</li>
<li>9039771174</li>
<li>9039771174</li>
<ul>
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
How can I get the numeric value from an string?
In my case string is R1350.00 and
Expected output:
1350
I tried the following:
$result = preg_replace("/[^a-zA-Z0-9]+/", "", 'R1350.00');
but I also want to remove the last two string 00. It is an amount value in ZAR. and I have to store the integer value in my database.
You can use str_replace function and then number_format
$str = 'R1350.00';
$str = str_replace('R',''.$str);
$str = number_format($str,0,'','');
echo $str;
//output 1350
try this one
$str="R1350.00";
$val=explode(".",$str);
echo substr($val[0],1);
//output 1350
Try this :
<?php
$string = "R1350.00";
preg_match("/(\d+\.\d{1,2})/",$string , $number);
echo $number[0];
?>
OR if you want to remove the .00, use this
preg_match("/(\d+)/",$string , $number);
If it's always going to be that format and length, you could use substr() like so:
$result = substr("R1350.00", 1, -3); // Output: 1350
EDIT: If the first character is always R (or a letter, rather) and there's always a decimal place not needed, then you can also use explode() on the decimal point and apply a substr() again. Like so:
$arrResult = explode(".", $result);
$strResult = substr($arrResult[0], 1); // Output: 1350
Here's an easy way to achieve that. First, replace anything that's not a number or a dot. That will leave your string with 1350.00. Then, just add zero to the number to make it an integer - effectively removing the decimal point and trailing zeroes.
<?php
$result = preg_replace('/[^0-9.]/', '', 'R1350.00') + 0;
print $result;
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
nickb originally provided these codes. What this originally does is that, when a user enters a text, it will convert it into a acronym by getting the first letters of every word entered. What I want to do now is to include the Last word of the text entered as part of the output. Example: if the user enters Automated Teller Machine, then the output would be: ATM Machine. So far, this is what I came up, unfortunately, I am at a loss right now and is desperate to get this working. Please help.
function convert($text)
{
$acronym = array();
$text2 = explode(' ', $text);
foreach(explode( ' ', $text) as $word)
{
$acronym[] = strtoupper( $word[0]);
}
$count = str_word_count($acronym);
array_push($acronym, $text2[$count]);
echo $text2[$count];
return implode('', $acronym);
}
It looks like you're off-by-one - use $count-1 in the array.
However, your code can be improved to this:
function convert($text) {
return preg_replace('/\b(.).*?\b\s*/',"$1",$text).strrchr($text," ");
}
// input: convert("Department of Redundancy Department");
// output: DoRD Department
It looks like that it's not clear to you what the code does. So let's write new code from scratch, but just don't copy it over but you should type it. All functions I use here are documented in the PHP manual. If a function is new to you or you don't know about the one or other parameter, just read it up and learn:
$words = str_word_count($text, 2);
This line of code extracts all words from $text into an array $words.
To get the last word, you only need to obtain the last array entry:
$last_word = end($words);
So this is already half the work to be done. Now you want to extract all first letters:
$first_letters = array();
foreach ($words as $word) {
$first_letters[] = substr($word, 0, 1);
}
Having that done, all first letters are in the array $first_letters and the last word is in the string variable $last_word. With one caveat. If there were no words in the $text, then this won't work. Just saying, check that yourself.
So now let's compile the final string:
$buffer = implode('', $first_letters);
is an easy way to convert the array into a string. And then you only need to add a space and the last word:
$buffer .= ' ';
That is adding a space character (obvious, right?) and not finally:
$buffer .= $last_word;
brings everything together.
Happy coding.