Strip all whitespace and include # at beginning of Username [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
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,'#');

Related

Space in # mention username and lowercase in link

I am trying to create a mention system and so far I've converted the #username in a link. But I wanted to see if it is possible for it to recognise whitespace for the names. For example: #Marie Lee instead of #MarieLee.
Also, I'm trying to convert the name in the link into lowercase letters (like: profile?id=marielee while leaving the mentioned showed with the uppercased, but haven't been able to.
This is my code so far:
<?php
function convertHashtags($str) {
$regex = '/#+([a-zA-Z0-9_0]+)/';
$str = preg_replace($regex, strtolower('$0'), $str);
return($str);
}
$string = 'I am #Marie Lee, nice to meet you!';
$string = convertHashtags($string);
echo $string;
?>
You may use this code with preg_replace_callback and an enhanced regex that will match all space separated words:
define("REGEX", '/#\w+(?:\h+\w+)*/');
function convertHashtags($str) {
return preg_replace_callback(REGEX, function ($m) {
return '$0';
}, $str);
}
If you want to allow only 2 words then you may use:
define("REGEX", '/#\w+(?:\h+\w+)?/');
You can filter out usernames based on alphanumeric characters, digits or spaces, nothing else to extract for it. Make sure that at least one character is matched before going for spaces to avoid empty space match with a single #. Works for maximum of 2 space separated words correctly for a username followed by a non-word character(except space).
<?php
function convertHashtags($str) {
$regex = '/#([a-zA-Z0-9_]+[\sa-zA-Z0-9_]*)/';
if(preg_match($regex,$str,$matches) === 1){
list($username,$name) = [$matches[0] , strtolower(str_replace(' ','',$matches[1]))];
return "<a href='profile?id=$name'>$username</a>";
}
throw new Exception('Unable to find username in the given string');
}
$string = 'I am #Marie Lee, nice to meet you!';
$string = convertHashtags($string);
echo $string;
Demo: https://3v4l.org/e2S8C
If you want the text to appear as is in the innerHTML of the anchor tag, you need to change
list($username,$name) = [$matches[0] , strtolower(str_replace(' ','',$matches[1]))];
to
list($username,$name) = [$str , strtolower(str_replace(' ','',$matches[1]))];
Demo: https://3v4l.org/dCQ4S

preg_replace vs trim PHP

I am working with a slug function and I dont fully understand some of it and was looking for some help on explaining.
My first question is about this line in my slug function $string = preg_replace('# +#', '-', $string); Now I understand that this replaces all spaces with a '-'. What I don't understand is what the + sign is in there for which comes after the white space in between the #.
Which leads to my next problem. I want a trim function that will get rid of spaces but only the spaces after they enter the value. For example someone accidentally entered "Arizona " with two spaces after the a and it destroyed the pages linked to Arizona.
So after all my rambling I basically want to figure out how I can use a trim to get rid of accidental spaces but still have the preg_replace insert '-' in between words.
ex.. "Sun City West " = "sun-city-west"
This is my full slug function-
function getSlug($string){
if(isset($string) && $string <> ""){
$string = strtolower($string);
//var_dump($string); echo "<br>";
$string = preg_replace('#[^\w ]+#', '', $string);
//var_dump($string); echo "<br>";
$string = preg_replace('# +#', '-', $string);
}
return $string;
}
You can try this:
function getSlug($string) {
return preg_replace('#\s+#', '-', trim($string));
}
It first trims extra spaces at the beginning and end of the string, and then replaces all the other with the - character.
Here your regex is:
#\s+#
which is:
# = regex delimiter
\s = any space character
+ = match the previous character or group one or more times
# = regex delimiter again
so the regex here means: "match any sequence of one or more whitespace character"
The + means at least one of the preceding character, so it matches one or more spaces. The # signs are one of the ways of marking the start and end of a regular expression's pattern block.
For a trim function, PHP handily provides trim() which removes all leading and trailing whitespace.

PHP string control on chars and numbers only [duplicate]

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);

How to convert a string to alphanumeric and convert spaces to dashes? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I'd like to take a string, strip it of all non-alphanumeric characters and convert all spaces into dashes.
I use the following code whenever I want to convert headlines or other strings to URL slugs. It does everything you ask for by using RegEx to convert any string to alphanumeric characters and hyphens.
function generateSlugFrom($string)
{
// Put any language specific filters here,
// like, for example, turning the Swedish letter "å" into "a"
// Remove any character that is not alphanumeric, white-space, or a hyphen
$string = preg_replace('/[^a-z0-9\s\-]/i', '', $string);
// Replace all spaces with hyphens
$string = preg_replace('/\s/', '-', $string);
// Replace multiple hyphens with a single hyphen
$string = preg_replace('/\-\-+/', '-', $string);
// Remove leading and trailing hyphens, and then lowercase the URL
$string = strtolower(trim($string, '-'));
return $string;
}
If you are going to use the code for generating URL slugs, then you might want to consider adding a little extra code to cut it after 80 characters or so.
if (strlen($string) > 80) {
$string = substr($string, 0, 80);
/**
* If there is a hyphen reasonably close to the end of the slug,
* cut the string right before the hyphen.
*/
if (strpos(substr($string, -20), '-') !== false) {
$string = substr($string, 0, strrpos($string, '-'));
}
}
Ah, I have used this before for blog posts (for the url).
Code:
$string = preg_replace("/[^0-9a-zA-Z ]/m", "", $string);
$string = preg_replace("/ /", "-", $string);
$string will contain the filtered text. You can echo it or do whatever you want with it.
$string = preg_replace(array('/[^[:alnum:]]/', '/(\s+|\-{2,})/'), array('', '-'), $string);

How do I strip all spaces out of a string in PHP? [duplicate]

This question already has answers here:
How can strip whitespaces in PHP's variable?
(15 answers)
Closed 3 years ago.
How can I strip / remove all spaces of a string in PHP?
I have a string like $string = "this is my string";
The output should be "thisismystring"
How can I do that?
Do you just mean spaces or all whitespace?
For just spaces, use str_replace:
$string = str_replace(' ', '', $string);
For all whitespace (including tabs and line ends), use preg_replace:
$string = preg_replace('/\s+/', '', $string);
(From here).
If you want to remove all whitespace:
$str = preg_replace('/\s+/', '', $str);
See the 5th example on the preg_replace documentation. (Note I originally copied that here.)
Edit: commenters pointed out, and are correct, that str_replace is better than preg_replace if you really just want to remove the space character. The reason to use preg_replace would be to remove all whitespace (including tabs, etc.).
If you know the white space is only due to spaces, you can use:
$string = str_replace(' ','',$string);
But if it could be due to space, tab...you can use:
$string = preg_replace('/\s+/','',$string);
str_replace will do the trick thusly
$new_str = str_replace(' ', '', $old_str);

Categories