How to replace space with new line [closed] - php

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>

Related

How to replace only a specific word from the end of the string in PHP? [closed]

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 2 years ago.
Improve this question
I have two string variables like this
$string1 = 'this is my house';
$string2 = 'this house is mine';
I need a method to replace 'house' with 'dog' only if 'house' is the last word of the string.
For example, this code
function replace($input_string, $search_string, $replace_string){
//do the magic here!
}
$string1 = replace($string1, 'house','dog');
$string2 = replace($string2, 'house','dog');
echo $string1;
echo $string2;
desired return will be...
this is my dog
this house is mine
Based on the conditions you mentioned you can do something like below. Find the word count and then check is home available in the string and then find the index of the house . So then you can check does that index match to last index of the word array (count($wordArray)) - 1)
$string1 = 'this is my house';
$string2 = 'this house is mine';
$wordArray = explode(' ', $string1); // make the array with words
//check the conditions you want
if (in_array('house', $wordArray) && (array_search('house', $wordArray) == (count($wordArray)) - 1)) {
$string1 = str_replace('house', 'dog', $string1);
}
echo $string1;
You are probably looking for something like this:
function replace($str,$from,$to){
$str = preg_replace('~('.preg_quote($from).')$~',$to,$str);
return $str;
}
Please note that documentation says to not to use preg_quote in preg_replace, but honestly I don't know why. If you know, please comment.

Get the string after the second underscore in PHP [closed]

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 2 years ago.
Improve this question
1_0_This is string
456_1_This_is_other_string_next
1999999_12_Is-string-too
How to get: This is string, This_is_other_string_next, Is-string-too
Thanks
Just an example to think about:
echo explode('_', '1_0_This is string', 3)[2];
echo explode('_', '1999999_12_Is-string-too', 3)[2];
You can trying exploding the original string using _ as a delimiter using explode(string $delimiter, string $string [, int $limit = PHP_INT_MAX]): array (see http://php.net/manual/en/function.explode.php).
Than you can count the number of items in the resulting array and return something accordingly.
Example ...
$string = "1_0_This is string";
$parts = explode('_', $string);
$result = "";
if (count($parts) >= 3) {
$result = $parts[2];
}
print $result;
Using preg_replace with a limit
echo preg_replace('/[^_]+_/', '', '1999999_12_Is-string-too', 2);
Output
Is-string-too
The Regex is simple. Match anything not _ (more then one time, greedy) followed by a _. Limit 2 replacements.
Using Preg Split
print_r(preg_split('/^([^_]+_){2}/', '456_1_This_is_other_string_next', -1, PREG_SPLIT_NO_EMPTY));
Output
Array
(
[0] => This_is_other_string_next
)
Basically the same regex, but this one matches the first 2 times the pattern happens. You can do the same thing with preg_replace, but it's kind of pointless there.

Return numeric value from an string in PHP [closed]

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;

how to remove unwanted characters from string in PHP [closed]

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

Acronym + Last Word of the Entered Text. PHP [closed]

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.

Categories