php function to generate numbers and letters [closed] - php

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.

Related

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

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 replace some text in a paragraph with other text in PHP [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
<?php
$string="Hello how are ##you ? I want ##join you.";
echo $string;
// now I want replace all ##.... words with <a>##.....</a>
// example Hello how are <a>##you</a> ? I want <a>##join</a>you.
?>
Now I want replace all ##.... words with ##.....
example Hello how are ##you ? I want ##join you.
I'll let others go for regex solutions. I'll propose something that hopefully more readable.
The following code uses my Parser class from Paladio (it's under CC-BY 3.0), it works on UTF-8.
The code is explained in the comments:
<?php
$string = "Hello how are ##you ? I want ##join you.";
// now I want replace all ##.... words with <a>##.....</a>
//Create a parser object for the string
$parser = new Parser($string);
//Create a variable to hold the result
$result = '';
//While we haven't reached the end of the string
while($parser->CanConsume())
{
//Take all the text until the next '##' or the end of the string
// and add to the result the string taken
$result .= $parser->ConsumeUntil('##');
//If we take a '##'
if ($parser->Consume('##'))
{
//Take the text until the next whitespace or new line
$tag = $parser->ConsumeUntil(array(' ', "\t", "\r", "\n"));
//Add the new converted text to the result
$result .= '<a>###'.$tag.'</a>';
}
}
// example Hello how are <a>##you</a> ? I want <a>##join</a>you.
echo $result;
?>
Based on the comments, this is a modified version that will allow to detect words marked with any of the given strings ('##' and '**' in the example):
function autolink($ptext, $detc)
{
// declared whitespace for readability and performance
$whitespace = array(' ', "\t", "\r", "\n");
$parser = new Parser($ptext);
$result = '';
while($parser->CanConsume())
{
$result .= $parser->ConsumeUntil($detc);
if ($parser->Consume($detc))
{
$newtag = $parser->ConsumeUntil($whitespace);
$result .= '<a href='.$newtag.'>'.$newtag.'</a>';
}
}
return $result;
}
Example usage:
echo autolink("Hello how are ##you ? I want **join you.", array('##', '**'));
Outputs:
Hello how are <a href=you>you</a> ? I want <a href=join>join</a> you.
Tested on my local server.
Notes:
The instruction $parser->Consume($detc) will return the found string, so you can use it to branch, example:
$input = $parser->Consume(array('a', 'b'));
if ($input === 'a')
{
// do something
}
else if ($input === 'b')
{
// do something else
}
else /if ($input === null)/
{
// fallback case
}
The supported things to Consume are:
Given strings.
Arrays of strings.
Numbers (amount of characters).
Null (will consume a single character).
Parser uses mb_* functions for some of the operations^, and expects UTF-8. If you experience problems with encoding you want to call mb_internal_encoding('UTF-8'); before using Parser and convert your string to UTF-8 (I recommend iconv for this operation). ^: Some other parts are optimized using byte per byte operations.

How do write reg exp for string has structure like a-b-1 and a-b-1/d-e-2? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Sorry my english is not good. I have a problem, I want to compare two different string use reg exp. The first string has structure like a-b-1, ex: mobile-phone-1. And the second string has structure like a-b-1/d-e-2, ex: mobile-phone-1/nokia-asha-23. How can I do it? You can use preg_match() method or something method ... This method for two different string. Thanks so much!
Code demo:
if (preg_match("reg exp 1", string1)) { // do something }
if (preg_match("reg exp 2", string2)) { // do something }
P/S: shouldn't care too much about code demo
$pattern = '#[\w]+-[\w]+-[\d]+(/[\w]+-[\w]+-[\d]+)?#';
if (preg_match($pattern, $str, $matches)){
return $matches;
}
To match the shorter string use:
$pattern = '#[\w]+-[\w]+-[\d]+#';
To match the longer:
$pattern = '#[\w]+-[\w]+-[\d]+/[\w]+-[\w]+-[\d]+#';
To match the longer with even more dashes:
$pattern = '#[\w]+-[\w]+-[\d]+/[\w-]+[\d]+#';
if(preg_match("/^([a-z]+)-([a-z]+)-([0-9]+)$/i",$string1))
if(preg_match("/^([a-z]+)-([a-z]+)-([0-9]+)\/([a-z]+)-([a-z]+)-([0-9]+)$/i",$string2))
'i' in the end is for case sensitivity.
Regular expression with explanation. Solved by step by step.
$text1='mobile is for you--phone-341/nokia-asha-253'; //sample string 1
$text2='mobile-phone-341'; //sample string 2
$regular_expression1='(\w)'; // Word (mobile)
$regular_expression2='(-)'; // Any Single Character (-)
$regular_expression3='(\w)'; // Word (phone)
$regular_expression4='(-)'; // Any Single Character (-)
$regular_expression5='(\d+)'; // Integer Number (341)
$regular_expression6='(\/)'; // Any Single Character (/)
$regular_expression7='(\w)'; // Word (nokia)
$regular_expression8='(-)'; // Any Single Character (-)
$regular_expression9='(\w)'; // Word (asha)
$regular_expression10='(-)'; // Any Single Character (-)
$regular_expression11='(\d)'; // Integer Number (253)
if ($c=preg_match_all ("/".$regular_expression1.$regular_expression2.$regular_expression3.$regular_expression4.$regular_expression5.$regular_expression6.$regular_expression7.$regular_expression8.$regular_expression9.$regular_expression10.$regular_expression11."/is", $text1))
{
echo "a-b-1/d-e-2 format string";
}
else
{
echo "Not in a-b-1/d-e-2";
}
echo "<br>------------------------<br>"; //just for separation
if ($c=preg_match_all ("/".$regular_expression1.$regular_expression2.$regular_expression3.$regular_expression4.$regular_expression5."/is", $text2))
{
echo "a-b-1 formate string";
}
else
{
echo "Not in a-b-1 format";
}

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