Scramble a PHP string - php

I want to create Unique ID for my site users in this format
pubID-john_34032
So I want to do this using the email string.
I have this pseudo code (but I want it faster and more logical if that makes sense)
How do I write my Pseudo code as PHP?
<?php
$var e(mysqlescape(get(emailform));
$var r(rand(3,34);
$var ex=(pubID-);
$var e=(replace(#/.); //users may enter 1#site.com so replace the at and .
$var e(first4strTo(e)); // get first four letters, example 1sit
$var e(e)+r(); // e is now 1site-1547
$var printStr e+ex //join the 1site-1547 with pubID- and done
?>

Unique Id in PHP there is uniqid. You can append that to whatever string. Why reinvent the wheel?

Use str_replace() to remove the # and . characters then use uniqid() to generate a unique identifier. Finally, concatenate them all together.
$email = 'user#gmail.com';
$str = 'pubID-' . str_replace(array('#', '.'), '', $email) . '_' . uniqid();
echo $str;

I don't have the reputation points to respond on Emmanuel N's answer.
Here's how to use uniqid and just grab the first part of the email address.
uniqid(substr($email, 0, strpos($email, '#')) . '_')

I fail to see your reasoning here. Why: pubID-john_34032
Couldn't you use the the user's name and append an auto incrementing id generated by your database? Something like:
calvinfroedge_23923
Then all you have to do is replace non whitelisted characters in the names and put an underscore between the name and the id.

Related

Working with strings - PHP

I need some PHP help with strings.
I have a textbox field where users will enter a facebook profile link.
Example: http://facebook.com/zuck
Now the problem is I need to have EXACTLY this string: "http://graph.facebook.com/zuck".
Inputs could be anything like:
http://facebook.com/zuck
http://www.facebook.com/zuck
www.facebook.com/zuck
facebook.com/zuck
What's the best way to do that? Thank you in advance.
To accept anything in the format of facebook.com/username where username is alphanumeric with dots, dashes, and underscores (not sure what Facebook allows exactly):
if (preg_match('%facebook.com/([a-z0-9._-]+)%i', $input, $m))
{
echo 'http://graph.facebook.com/', $m[1], "\n";
}
Why don't you just ask the user for their username? Instead of accepting a wide variety of input, design the form so that they only have to put in their username.
Something along the lines of this;
This way, you don't even have to validate or store anything other than their username. This could be super helpful down the road when Facebook moves fast and breaks stuff, like the URLs of users. Or if you want to form URLs for something other than graph API, you won't have to pull apart an existing URL.
If given inputs will be always as the ones you give i think that strstr function would hadle this
$array = array('http://facebook.com/zuck', 'http://www.facebook.com/buck', 'www.facebook.com/luck', 'facebook.com/nuck');
foreach($array as $data)
{
if(strstr($data, 'facebook.com/'))
{
echo 'http://graph.'.strstr($data, 'facebook.com/') . '<br>';
}
}
This will output
http://graph.facebook.com/zuck
http://graph.facebook.com/buck
http://graph.facebook.com/luck
http://graph.facebook.com/nuck
Find the last slash in the input
$lastpos = strrchr ( $input , '/' )
Manually concatenate the url and everything after that last slash.
$new_url = 'http://www.facebook.com' . substr($input, $lastpos);
$url = 'http://facebook.com/zuck';
$array = explode('/', str_replace('http://', '', $url));
$username = $array[1];
$finalurl = 'http://graph.facebook.com/zuck'.$username;
echo $finalurl;
This will work with any format of input URL.
Something along the lines of:
Pattern:
(https?://)?(www\.)?(.+?)\/([^/]+)
Replace with:
http://graph.$3/$4
Test it here:
http://www.regexe.com/

Pulling a number and prefix from filename using PHP

I am currently using the following function to grab the product code number for a filename such as "62017 THOR.jpg"
$number = (int) $value;
Leaving me with 62017
The trouble is some of these files have prefixes which need to be left in place ie "WST 62017.jpg"
So im after
WST 62017
not
62017
Could someone help me, either redo what im using or alter ?
replace all characters except the numbers from the image name and get only numbers.
$number = preg_replace("~[^0-9]~", "", $value);
If you want to capture everything before the number and the number as well, you can use:
$value = "WST 62017.jpg";
$number = preg_replace('/^(.*?\d*)\..*/',"$1",trim($value));
// $number is "WST 62017"
See it
You could do it like this:
$value = preg_replace('/^(.*\d+).*$/', '\1', $filename);
It should replace everything after the first numeric value with nothing, leaving everything in front of it in place. Note that you wont't be able to cast the number to int, then.

Separating the extention from its domain name

I want to work around email addresses and I want to explode them using php's explode function.
It's ok to separate the user from the domain or the host doing like this:
list( $user, $domain ) = explode( '#', $email );
but when trying to explode the domain to domain_name and domain_extention I realised that when exploding them using the "." as the argument it will not always be foo.bar, it can sometimes be foo.ba.ar like fooooo.co.uk
so how to separate "fooooo.co" from "uk" and let the co with the fooooo. so finally I will get the TLD separated from the other part.
I know that co.uk is supposed to be treated as the TLD but it's not official, like fooooo.nat.tn or fooooo.gov.tn
Thank You.
Just use strripos() to find the last occurrence of ".":
$blah = "hello.co.uk";
$i = strripos($blah, ".");
echo "name = " . substr($blah, 0, $i) . "\n";
echo "TLD = " . substr($blah, $i + 1) . "\n";
Better use imap_rfc822_parse_adrlist or mailparse_rfc822_parse_addresses to parse the email address if available. And for removing the “public suffix” from the domain name, see my answer to Remove domain extension.
Expanding on Oli's answer...
substr($address, (strripos($address, '.') + 1));
Will give the TLD without the '.'. Lose the +1 and you get the dot, too.
end(explode('.', $email)); will give you the TLD. To get the domain name without that, you can do any number of other string manipulation tricks, such as subtracting off that length.

Using regex to fix phone numbers in a CSV with PHP

My new phone does not recognize a phone number unless its area code matches the incoming call. Since I live in Idaho where an area code is not needed for in-state calls, many of my contacts were saved without an area code. Since I have thousands of contacts stored in my phone, it would not be practical to manually update them. I decided to write the following PHP script to handle the problem. It seems to work well, except that I'm finding duplicate area codes at the beginning of random contacts.
<?php
//the script can take a while to complete
set_time_limit(200);
function validate_area_code($number) {
//digits are taken one by one out of $number, and insert in to $numString
$numString = "";
for ($i = 0; $i < strlen($number); $i++) {
$curr = substr($number,$i,1);
//only copy from $number to $numString when the character is numeric
if (is_numeric($curr)) {
$numString = $numString . $curr;
}
}
//add area code "208" to the beginning of any phone number of length 7
if (strlen($numString) == 7) {
return "208" . $numString;
//remove country code (none of the contacts are outside the U.S.)
} else if (strlen($numString) == 11) {
return preg_replace("/^1/","",$numString);
} else {
return $numString;
}
}
//matches any phone number in the csv
$pattern = "/((1? ?\(?[2-9]\d\d\)? *)? ?\d\d\d-?\d\d\d\d)/";
$csv = file_get_contents("contacts2.CSV");
preg_match_all($pattern,$csv,$matches);
foreach ($matches[0] as $key1 => $value) {
/*create a pattern that matches the specific phone number by adding slashes before possible special characters*/
$pattern = preg_replace("/\(|\)|\-/","\\\\$0",$value);
//create the replacement phone number
$replacement = validate_area_code($value);
//add delimeters
$pattern = "/" . $pattern . "/";
$csv = preg_replace($pattern,$replacement,$csv);
}
echo $csv;
?>
Is there a better approach to modifying the CSV? Also, is there a way to minimize the number of passes over the CSV? In the script above, preg_replace is called thousands of times on a very large String.
If I understand you correctly, you just need to prepend the area code to any 7-digit phone number anywhere in this file, right? I have no idea what kind of system you're on, but if you have some decent tools, here are a couple options. And of course, the approaches they take can presumably be implemented in PHP; that's just not one of my languages.
So, how about a sed one-liner? Just look for 7-digit phone numbers, bounded by either beginning of line or comma on the left, and comma or end of line on the right.
sed -r 's/(^|,)([0-9]{3}-[0-9]{4})(,|$)/\1208-\2\3/g' contacts.csv
Or if you want to only apply it to certain fields, perl (or awk) would be easier. Suppose it's the second field:
perl -F, -ane '$"=","; $F[1]=~s/^[0-9]{3}-[0-9]{4}$/208-$&/; print "#F";' contacts.csv
The -F, indicates the field separator, the $" is the output field separator (yes, it gets assigned once per loop, oh well), the arrays are zero-indexed so second field is $F[1], there's a run-of-the-mill substitution, and you print the results.
Ah programs... sometimes a 10-min hack is better.
If it were me... I'd import the CSV into Excel, sort it by something - maybe the length of the phone number or something. Make a new col for the fixed phone number. When you have a group of similarly-fouled numbers, make a formula to fix. Same for the next group. Should be pretty quick, no? Then export to .csv again, omitting the bad col.
A little more digging on my own revealed the issues with the regex in my question. The problem is with duplicate contacts in the csv.
Example:
(208) 555-5555, 555-5555
After the first pass becomes:
2085555555, 208555555
and After the second pass becomes
2082085555555, 2082085555555
I worked around this by changing the replacement regex to:
//add escapes for special characters
$pattern = preg_replace("/\(|\)|\-|\./","\\\\$0",$value);
//add delimiters, and optional area code
$pattern = "/(\(?[0-9]{3}\)?)? ?" . $pattern . "/";

PHP: Regular Expression to delete text from a string if condition is true

I have a variable containing a string. The string can come in several ways:
// some examples of possible string
$var = 'Tom Greenleaf (as John Dunn Hill)'
// or
$var = '(screenplay) (as The Wibberleys) &'
// or
$var = '(novella "Four Past Midnight: Secret Window, Secret Garden")'
I need to clean up the string to get only the first element. like this:
$var = 'Tom Greenleaf'
$var = 'screenplay'
$var = 'novella'
I know this is a bit complicated to do but there is a pattern we can use.
Looking at the first variable, we can first check if the string contains the text ' (as'. If it does then we need to delete ' (as' and everything that comes after that.
In the second variable the rule we made in the first one also applies. We just need also to delete the parenthesis .
In the third variable if ' (as' was not found we need to get the first word only and then delete the parenthesis.
Well, thas all. I just need someone to help me do it because I'm new to PHP and I don't know regular expressions.... or another way to do it.
Thanks!!!!
actually, there's no need for complex regex
$var = 'Tom Greenleaf (as John Dunn Hill)';
$var = '(novella "Four Past Midnight: Secret Window, Secret Garden")';
$var = '(screenplay) (as The Wibberleys) &';
if ( strpos($var,"(as") !== FALSE ){
# get position of where (as is
$ind = strpos($var,"(as");
$result = substr($var,0,$ind);
}else {
# if no (as, split on spaces and get first element
$s = preg_split("/\s+/",$var);
$result = $s[0];
}
print preg_replace( "/\(|\)/","",$result);
Try this regular expression:
(?:^[^(]+|(?<=^\()[^\s)]+)
This will get you either anything up to the first parenthesis or the first word inside the first parenthesis. Together with preg_match:
preg_match('/(?:^[^(]+|(?<=^\\()[^\\s)]+)/', $var, $match);
try this one
^\((?<MATCH>[^ )]+)|^(?<MATCH>[^ ]+)

Categories