PHP string control on chars and numbers only [duplicate] - php

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Function to return only alpha-numeric characters from string?
Starting from $string = "hey hello 9times-%&";
I would like to replace all the chars that are NOT numeric[0-9] or [a-z,A-Z] type.
Is there a good method to show this process control?
EDITED
i forgot that i need to leave blank space bar blank spaces, i mean:
"hey &/k" must return as "hey k" and NOT as "heyk"

<?php
$string = "hey hello 9times-%&";
$string = preg_replace('/[^0-9A-Z\s]+/i', '', $string);
echo $string;
?>

preg_replace('/[^ \w]+/i', '', $string);
That will work as well. See the codepad example.

What about preg_replace:
$clean = preg_replace('/[^0-9a-z\s]/i','',$input);

Related

How to allow specific values in my string [duplicate]

This question already has answers here:
Remove all special characters from a string [duplicate]
(3 answers)
Closed 5 years ago.
I want to replace space with "|" and i want only numbers and alphabets and star(*) in the sting
And i have tried str_replace() funtion but it replace the space with | , but i want to validate
echo $text= str_replace(' ','|', "This is some $123 Money");
output
This|is|some|$123|Money
what i expect is
This|is|some|123|Money
I don't want any other special characters in my output
Any Suggestions
Thanks in Advance
You can use preg_replace to remove all special characters from your string.
Example
echo $text= str_replace(' ','|', preg_replace('/[^A-Za-z0-9 ]/', '',"This is some $123 Money"));
Output
This|is|some|123|Money
Here is the working demo for you: https://3v4l.org/M456J
<?php
$s = "This is some $123 Money";
$result = preg_replace("/[^a-zA-Z0-9]+/", "|", $s);
echo $result;
Output:
This|is|some|123|Money

Strip all whitespace and include # at beginning of Username [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
So this post is in two parts:
I have found a few different ways of either removing whitespace at the beginning & end of a string or sending out an error if there is any whitespace - but how can I remove all whitespace in a string ($name)? < By this if someone enters their full name with spaces the script should automatically put their first and last name together without the whitespace without putting out error.
Also, how can I make sure a # sign is a default at the beginning of the string like the twitter username?
If by whitespace you mean the space character then you can use str_replace:
$string = 'There are two spaces here .';
echo str_replace(' ', '', $string); //Outputs "Therearetwospaceshere."
If you need to strip line-breaks, or tabs as well as spaces look at using preg_replace:
$string = "There are two spaces and a \n line break here.";
echo preg_replace('/\s+/', '', $string); //Outputs "Therearetwospacesandalinebreakhere."
For validating that the string begins with an # sign I would use a regular expression:
if (preg_match('/^#/', $string))
echo 'Begins with #';
else
echo 'Does not being with #';
Try str_replace():
$name = 'bill harrison jones';
$name = '#'.str_replace(' ', '', $name);
See demo
You can use trim() to remove the whitespace at the beginning and end of a string:
$string = " hello ";
$newstring = strim($string);
echo $newstring; // outputs "hello"
If you want to remove all whitespace from a string, you can use preg_replace():
$string = "hello
hello ";
$newstring = preg_replace('/\s+/', '', $string);
echo $newstring; // outputs "hellohello"
You can check the beginning character using preg_match():
$string = "#esqew";
if (preg_match('/#([\w]+)/', $string) == 1) {
// string starts with "#"
}
Debuggex
Please be careful though, as Twitter usernames follow a much stricter regex than you might think.
Your first question is confusing. It sounds like you have already solved your problem. Nonetheless, str_replace is the function you want.
Your second ought to belong in a separate question. However, a string is an array of characters. So I imagine the following would work
$name = array_unshift($name, '#');
For removing all space and white space ( like break ) use this
$string = preg_replace('/\s+/', '', $string);
For check #
if($string[0] != '#')
echo 'Error';
else
//do something
If you want to add # when username is without # use this code
$string = '#' . ltrim($string,'#');

Remove a word at the beginning of a string [duplicate]

This question already has answers here:
Remove a string from the beginning of a string
(10 answers)
Closed 9 years ago.
$str = "hello world, what's up";
How can I check $str to see if there is a word "hello" and remove it only if it is at the beginning of the string (first 5 letters)?
You can use substr, which is faster than preg_replace:
$str = "hello world, what's up?";
$pre = "hello ";
if(substr($str, 0, strlen($pre)) === $pre)
$str = substr($str, strlen($pre));
echo $str; // world, what's up?
^ indicates the beginning of the string, and an i flag for a case-insensitive match as per #Havenard's comment.
preg_replace('/^hello/i', '', $str);
preg_replace('/^hello\b/U', '', $str);
This will replace 'hello' in 'hello world' but not in 'helloworld'. Because it's replacing just one instance at the start of the string, the amount of cpu use is negligible.

How to use regex to delete everything except some words? [duplicate]

This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
Regular expression: match all words except
I need your help for using Regex in PHP to negate a selection. So I have a string like this :
"Hello my name is tom"
What I need to do is to delete everything from this string witch is not "tom" or "jack" or "alex" so I tried :
$MyString = "Hello my name is tom"
print_r(preg_replace('#^tom|^jack|^alex#i', '', $MyString));
But it's not working...
Can you help me with that ?
Thanks
If you want to delete everything except something, may be it's better done the other way around: capture the something only? For example...
$testString = 'Hello my name is tom or jack';
$matches = array();
preg_match_all('/\b(tom|jack|alex)\b/i', $testString, $matches);
$result = implode('', $matches[0]);
echo $result; // tomjack
What you've tried to do is use a character class syntax ([^s] will match any character but s). But this doesn't work with series of characters, there's no such thing as 'word class'. )
If you want to remove everything that is not "tom" or "jack" or "alex" you can use the following:
$MyString = "Hello my name is jack";
print_r(preg_replace('#.*(tom|jack|alex)#i', '$1', $MyString));
This replaces the whole string with just the matched name.
regex:
\b(?!tom|jack|alex)[^\s]+\b
You could match what you want and then reconstruct the string:
$s = 'hello my name is tom, jack and alex';
if (preg_match_all('/(?:tom|jack|alex)/', $s, $matches)) {
print_r($matches);
$s = join('', $matches[0]);
} else {
$s = '';
}
echo $s;
Output:
tomjackalex

Trim multiple characters using php [duplicate]

This question already has answers here:
PHP ltrim behavior with character list
(2 answers)
Closed 12 months ago.
How to trim multiple characters at begin and end of string.
string should be something like {Hello {W}orld}.
i want to trim both { and } at begin and end.
don't want to use multiple trim function.
Use the optional second argument to trim which allows you to specify the list of characters to trim:
<?php
$str = "{Hello {W}orld}";
$str = trim($str, "{}");
echo "Trimmed: $str";
Output:
Trimmed: Hello {W}orld
Is there always a character at the beginning and at the end, that you want to remove? If so you could just use the following:
<?php
$string = '{Hello {W}orld}';
echo substr( $string, 1, strlen( $string )-2 );
?>
See: http://codepad.org/IDbG6Km2

Categories