php cleanup phone variable - php

Im wanting to record on a database, peoples phone numbers. Since people enter numbers differently(based on area codes) etc, i want to normalize whatever they input into a standard manner before it goes up to a database, then when i read it back from the database and put on the page, that it comes out like this 1-954-999-9999 in this format to which i can then append the 1-954-999-9999 and can be clicked from the web app / or normal site to make a call.
All this said, i have a question.
On POST this is how im handling it
$compBizNumber = mysqli_real_escape_string($c2d, $_POST['compBizNumber']) ;
$compBizNumber = str_replace("(", "-", $compBizNumber);
$compBizNumber = str_replace(")", "-", $compBizNumber);
$compBizNumber = str_replace(" ", "-", $compBizNumber);
$compBizNumber = filter_var($compBizNumber,FILTER_SANITIZE_NUMBER_INT) ;
Is there a way to replace multiple characters in one go??
how can i go about this?
Thanks in advanced.

str_replace accepts an array as the first (and second parameter) so this will do:
$compBizNumber = str_replace(array("(", ")", " "), "-", $compBizNumber);
However, a more flexible way would be to use a regular expression to replace all non-numeric characters:
$compBizNumber = preg_replace("/[^0-9]/", "-", $compBizNumber);
This way you don't have to add all possible characters a user would enter into str_replace.

Why not use a regex to remove all except numbers:
$myNumber = "+31 (0) 43 - 123 345 67";
preg_replace("/[^0-9]/","", $myNumber);
http://codepad.org/30vUqWWC
However, beware of the + I guess you'd have to replace that with 00 instead of nothing in order to make the number work? Not 100% sure about that one.

Related

I want to get "0.8" from my string using PHP

I have a string
$string = "2.5 lakh videos views 0.8";
Now I want to get "0.8" from above string using PHP.
To get the last 3 characters:
$string = "2.5 lakh videos views 0.8";
$valSubstr = substr($string, -3);
echo $valSubstr;
To get the last "part" of the sentence. (this way you don't have to care about the count of characters in your number)
$string = "2.5 lakh videos views 0.8";
$partsString = explode(' ', $string);
$valExplode = $partsString[count($partsString) - 1];
echo $valExplode;
Both methods are bad, because you can only hope your data is in the format you expect it to be. But if your data is always in the format you showed, it would work. You can add a regex to check for unwanted characters like a trailing ".".
You can use php function substr() like this substr($string,-3);.

How to add slash after every string in PHP?

How i can add a slash or ; after every string. Here i have an Example:
This is what i have
"SKU" "TITLE" "LINK" "LINK2" "PRICE" "World of Warcraft"
But i will have like that
"SKU";"TITLE";"LINK";"LINK2";"PRICE";"World of Warcraft"
How i can made this? I work with affiliate and this Partner dont give CSV. Its only an TXT file.
So, how i can add slash into every "string"?
i already tried to add ; after every 2nd ". But it dont work with my code...
also tried with str_replace()
str_replace(" ", ";", $item);
The solution using preg_replace function:
$str = '"61926182767182" "DAS GEILE GAME" "HTTP://google.com/123129182691239" "HTTP://google.com/123129182691239" "32.59"';
$str = preg_replace("/(\"[^\"]+\")\s/", "$1;", $str);
print_r($str); // '"61926182767182";"DAS GEILE GAME";"HTTP://google.com/123129182691239";"HTTP://google.com/123129182691239";"32.59"'
(this approach can be easily extended if there would be tabs instead of spaces in the input string OR if there may be multiple spaces between words. It's more flexible)
You can split string by " " delimiter using explode() and join result array with ";" string using implode()
$str = implode('";"', explode('" "', $str))
See result in demo

Replace a character only in one special part of a string

When I've a string:
$string = 'word1="abc.3" word2="xyz.3"';
How can I replace the point with a comma after xyz in xyz.3 and keep him after abc in abc.3?
You've provided an example but not a description of when the content should be modified and when it should be kept the same. The solution might be simply:
str_replace("xyz.", "xyz", $input);
But if you explicitly want a more explicit match, say requiring a digit after the ful stop, then:
preg_replace("/xyz\.([0-9])+/", 'xyz\${1}', $input);
(not tested)
something like (sorry i did this with javascript and didn't see the PHP tag).
var stringWithPoint = 'word1="abc.3" word2="xyz.3"';
var nopoint = stringWithPoint.replace('xyz.3', 'xyz3');
in php
$str = 'word1="abc.3" word2="xyz.3"';
echo str_replace('xyz.3', 'xyz3', $str);
You can use PHP's string functions to remove the point (.).
str_replace(".", "", $word2);
It depends what are the criteria for replace or not.
You could split string into parts (use explode or preg_split), then replace dot in some parts (eg. str_replace), next join them together (implode).
how about:
$string = 'word1="abc.3" word2="xyz.3"';
echo preg_replace('/\.([^.]+)$/', ',$1', $string);
output:
word1="abc.3" word2="xyz,3"

How to convert a nice page title into a valid URL string?

imagine a page Title string in any given language (english, arabic, japanese etc) containing several words in UTF-8. Example:
$stringRAW = "Blues & μπλουζ Bliss's ブルース Schön";
Now this actually needs to be converted into something thats a valid portion of a URL of that page:
$stringURL = "blues-μπλουζ-bliss-ブルース-schön"
just check out this link
This works on my server too!
Q1. What characters are allowed as valid URL these days? I remember having seen whol arabic strings sitting on the browser and i tested it on my apache 2 and all worked fine.
I guesse it must become: $stringURL = "blues-blows-bliss-black"
Q2. What existing php functions do you know that encode/convert these UTF-8 strings correctly for URL ripping them off of any invalid chars?
I guesse that at least:
1. spaces should be converted into dashes -
2. delete invalid characters? which are they? # and '&'?
3. converts all letters to lower case (or are capitcal letters valid in urls?)
Thanks: your suggestions are much appreciated!
this is solution which I use:
$text = 'Nevalidní Český text';
$text = preg_replace('/[^\\pL0-9]+/u', '-', $text);
$text = trim($text, "-");
$text = iconv("utf-8", "us-ascii//TRANSLIT", $text);
$text = preg_replace('/[^-a-z0-9]+/i', '', $text);
Capitals in URL's are not a problem, but if you want the text to be lowercase then simply add $text = strtolower($text); at the end :-).
I would use:
$stringURL = str_replace(' ', '-', $stringURL); // Converts spaces to dashes
$stringURL = urlencode($stringURL);
$stringURL = preg_replace('~[^a-z ]~', '', str_replace(' ', '-', $stringRAW));
Check this method: http://www.whatstyle.net/articles/52/generate_unique_slugs_in_cakephp
pick the title of your webpage
$title = "mytitle#$3%#$5345";
simply urlencode it
$url = urlencode($title);
you dont need to worry about small details but remember to identify your url request its best to use a unique id prefix in url such as /389894/sdojfsodjf , during routing process you can use id 389894 to get the topic sdojfsodjf .
Here is a short & handy one that does the trick for me
$title = trim(strtolower($title)); // lower string, removes white spaces and linebreaks at the start/end
$title = preg_replace('#[^a-z0-9\s-]#',null, $title); // remove all unwanted chars
$title = preg_replace('#[\s-]+#','-', $title); // replace white spaces and - with - (otherwise you end up with ---)
and of course you need to handle umlauts, currency signs and so forth depending on the possible input

Restrict text input to only allow five (5) words in PHP

I want to know how I can allow only five (5) words on text input using PHP.
I know that I can use the strlen function for character count, but I was wondering how I can do it for words.
You can try it like this:
$string = "this has way more than 5 words so we want to deny it ";
//edit: make sure only one space separates words if we want to get really robust:
//(found this regex through a search and havent tested it)
$string = preg_replace("/\\s+/", " ", $string);
//trim off beginning and end spaces;
$string = trim($string);
//get an array of the words
$wordArray = explode(" ", $string);
//get the word count
$wordCount = sizeof($wordArray);
//see if its too big
if($wordCount > 5) echo "Please make a shorter string";
should work :-)
If you do;
substr_count($_POST['your text box'], ' ');
And limit it to 4
If $input is your input string,
$wordArray = explode(' ', $input);
if (count($wordArray) > 5)
//do something; too many words
Although I honestly don't know why you'd want to do your input validation with php. If you just use javascript, you can give the user a chance to correct the input before the form submits.
Aside from all these nice solutions using explode() or substr_count(), why not simply use PHP's built-in function to count the number of words in a string. I know the function name isn't particularly intuitive for this purpose, but:
$wordCount = str_word_count($string);
would be my suggestion.
Note, this isn't necessarily quite as effective when using multibyte character sets. In that case, something like:
define("WORD_COUNT_MASK", "/\p{L}[\p{L}\p{Mn}\p{Pd}'\x{2019}]*/u");
function str_word_count_utf8($str)
{
return preg_match_all(WORD_COUNT_MASK, $str, $matches);
}
is suggested on the str_word_count() manual page
You will have to do it twice, once using JavaScript at the client-side and then using PHP at the server-side.
In PHP, use split function to split it by space.So you will get the words in an array. Then check the length of the array.
$mytextboxcontent=$_GET["txtContent"];
$words = explode(" ", $mytextboxcontent);
$numberOfWords=count($words);
if($numberOfWords>5)
{
echo "Only 5 words allowed";
}
else
{
//do whatever you want....
}
I didn't test this.Hope this works. I don't have a PHP environment set up on my machine now.
You could count the number of spaces...
$wordCount = substr_count($input, ' ');
i think you want to do it first with Javascript to only allow the user to insert 5 words (and after validate it with PHP to avoid bad intentions)
In JS you need to count the chars as you type them and keep the count of the words you write ( by incrementing the counter each space)
Take a look of this code: http://javascript.internet.com/forms/limit-characters-and-words-entered.html

Categories