Acronym + Last Word of the Entered Text. PHP [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
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.

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.

Match strings starts and end with particular character in a String using 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 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

How to replace space with new line [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
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>

php function to generate numbers and letters [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
So I need to create a function that will produce the following types of combinations:
Option #1: ### (can/needs to be 3 numbers)
Option #2: #*# (number, letter, number)
Option #3: #** (number, letter, letter)
Option #4: **# (letter, letter, number)
Option #5: *## (letter, number, number)
Option #6: * (letter, letter, letter)
The reason for this is to parse those possibilities against the FAA website to find the available codes. So if I can get the function created to create those possibilities, I can store them in a database and then write my function to loop over those, and push them to a curl method to scrape the response. I'm code blocked on how to create this function though
As an example:
Field 1: 123 - Field 2: 1B1 - Field 3: T8C
A possible way to do this is to simply add all characters to an array, loop over it 3x and just add em all together. Like so:
function return_all_possible_combos() {
$chars = array();
for($i=48;$i<=57;$i++) {
$chars[] = chr($i); // adds the characters 0-9 to the $chars array (48-57 are the positions of 0-9 in the ASCII table
}
for($i=65;$i<=90;$i++) {
$chars[] = chr($i); // adds the characters 0-9 to the $chars array (65-90 are the positions of A-Z in the ASCII table
}
// $chars now holds all values 0-9 and A-Z
$possible_values = array();
foreach($chars as $k=>$first_char) {
foreach($chars as $l=>$second_char) {
foreach($chars as $m=>$third_char) {
$possible_values[] = $first_char . $second_char . $third_char;
}
}
}
return $possible_values;
}
Your problem is quite trivial, you might use something like this:
<?
function randomString($format) {
$format = str_split($format);
$chars = str_split("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ");
$res = "";
foreach ($format as $f) {
if ($f=="#") $res .= rand(0,9);
else $res .= $chars[array_rand($chars)];
}
return $res;
}
?>
This basically returns random string the way you need it. For example:
<?
echo randomString("##**");
?>
Will return two numbers followed by two characters.
I wrote this without testing, so it might need a little tweaking, and I usually do not prefer writing code for other people problems, but this seemed like interesting, albeit trivial problem.
Let me know if this is what you need.

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

Categories