php remove all spaces from string

Php remove all spaces from string

(PHP 4, PHP 5, PHP 7, PHP 8)

trim — Strip whitespace (or other characters) from the beginning and end of a string

Description

Parameters

The string that will be trimmed.

Return Values

The trimmed string.

Examples

Example #1 Usage example of trim()

The above example will output:

Example #2 Trimming array values with trim()

The above example will output:

Notes

Note: Possible gotcha: removing middle characters

See Also

User Contributed Notes 18 notes

When specifying the character mask,
make sure that you use double quotes

= »
Hello World » ; //here is a string with some trailing and leading whitespace

Non-breaking spaces can be troublesome with trim:

// PS: Thanks to John for saving my sanity!
?>

It is worth mentioning that trim, ltrim and rtrim are NOT multi-byte safe, meaning that trying to remove an utf-8 encoded non-breaking space for instance will result in the destruction of utf-8 characters than contain parts of the utf-8 encoded non-breaking space, for instance:

non breaking-space is «\u» or «\xc2\xa0» in utf-8, «µ» is «\u» or «\xc2\xb5» in utf-8 and «à» is «\u» or «\xc3\xa0» in utf-8

$input = «\uµ déjà\u«; // » µ déjà «
$output = trim($input, «\u«); // «▒ déj▒» or whatever how the interpretation of broken utf-8 characters is performed

$output got both «\u» characters removed but also both «µ» and «à» characters destroyed

Care should be taken if the string to be trimmed contains intended characters from the definition list.

E.g. if you want to trim just starting and ending quote characters, trim will also remove a trailing quote that was intentionally contained in the string, if at position 0 or at the end, and if the string was defined in double quotes, then trim will only remove the quote character itself, but not the backslash that was used for it’s definition. Yields interesting output and may be puzzling to debug.

To remove multiple occurences of whitespace characters in a string an convert them all into single spaces, use this:

trim is the fastest way to remove first and last char.

This is the best solution I’ve found that strips all types of whitespace and it multibyte safe

Trim full width space will return mess character, when target string starts with ‘《’

[EDIT by cmb AT php DOT net: it is not necessarily safe to use trim with multibyte character encodings. The given example is equivalent to echo trim(«\xe3\80\8a», «\xe3\x80\x80»).]

if you are using trim and you still can’t remove the whitespace then check if your closing tag inside the html document is NOT at the next line.

there should be no spaces at the beginning and end of your echo statement, else trim will not work as expected.

If you want to check whether something ONLY has whitespaces, use the following:

Источник

How to remove spaces before and after a string?

I have two words spirited by space of course, and a lot of spaces before and after, what I need to do is to remove the before and after spaces without the in between once.

How can I remove the spaces before and after it?

php remove all spaces from string. Смотреть фото php remove all spaces from string. Смотреть картинку php remove all spaces from string. Картинка про php remove all spaces from string. Фото php remove all spaces from string

5 Answers 5

You don’t need regex for that, use trim():

This function returns a string with whitespace stripped from the beginning and end of str.

php remove all spaces from string. Смотреть фото php remove all spaces from string. Смотреть картинку php remove all spaces from string. Картинка про php remove all spaces from string. Фото php remove all spaces from string

For completeness (as this question is tagged regex ), here is a trim() reimplementation in regex:

php remove all spaces from string. Смотреть фото php remove all spaces from string. Смотреть картинку php remove all spaces from string. Картинка про php remove all spaces from string. Фото php remove all spaces from string

For some reason two solutions above didnt worked for me, so i came up with this solution.

php remove all spaces from string. Смотреть фото php remove all spaces from string. Смотреть картинку php remove all spaces from string. Картинка про php remove all spaces from string. Фото php remove all spaces from string

The question was about how to do it with regex, so:

That says ^ at the begining \s+ (white space) | or \s+$ (whitespace at the end) //g remove repeatedly. this same concept works in ‘ed’ (vi/vim)

sometimes it is better just to answer the question that was asked.

php remove all spaces from string. Смотреть фото php remove all spaces from string. Смотреть картинку php remove all spaces from string. Картинка про php remove all spaces from string. Фото php remove all spaces from string

php remove all spaces from string. Смотреть фото php remove all spaces from string. Смотреть картинку php remove all spaces from string. Картинка про php remove all spaces from string. Фото php remove all spaces from string

Not the answer you’re looking for? Browse other questions tagged php regex or ask your own question.

Related

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.9.17.40238

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

PHP: Removing whitespace characters.

This is a short guide on how to remove whitespace characters in PHP. In some cases, this is necessary if you are dealing with external data from users, files or other websites. Examples include telephone numbers, vehicle registration numbers and post codes.

Basically, any kind of data that needs to be cleaned up before you can continue processing it.

Removing spaces.

If you want to remove spaces from a string, you can use PHP’s native str_replace function like so:

If you run the code snippet above, you will see that we are left with: 12WD2039.

This is because we told the str_replace function to replace all space characters in our string with nothing.

However, this approach will not work with ‘special’ whitespace characters such as the “new line”.

Remove ALL whitespace characters.

If you need to remove ALL whitespace characters, then you can use the preg_replace function. This may be necessary if you encounter data that contains tabbed spaces or invisible end line characters.

With PHP’s preg_replace function, we can use regular expressions to search for and replace all whitespace characters:

If you run the PHP above, you’ll see that our regular expression removed the offending characters. If you replace the preg_replace line with the str_replace solution that we used in the first example, you will see that it only strips out the first character.

Remove spaces from the beginning and end of a string.

Sometimes, you might only want to remove spaces from the beginning and end of a string. In that case, the trim function is your best friend:

Источник

Remove excess whitespace from within a string

I receive a string from a database query, then I remove all HTML tags, carriage returns and newlines before I put it in a CSV file. Only thing is, I can’t find a way to remove the excess white space from between the strings.

What would be the best way to remove the inner whitespace characters?

11 Answers 11

Not sure exactly what you want but here are two situations:

Example:

php remove all spaces from string. Смотреть фото php remove all spaces from string. Смотреть картинку php remove all spaces from string. Картинка про php remove all spaces from string. Фото php remove all spaces from string

Or, replace with underscore, & nbsp; etc etc.

none of other examples worked for me, so I’ve used this one:

this replaces all tabs, new lines, double spaces etc to simple 1 space.

The above line of code will remove extra spaces, as well as leading and trailing spaces.

There are security flaws to using preg_replace(), if you get the payload from user input [or other untrusted sources]. PHP executes the regular expression with eval(). If the incoming string isn’t properly sanitized, your application risks being subjected to code injection.

In my own application, instead of bothering sanitizing the input (and as I only deal with short strings), I instead made a slightly more processor intensive function, though which is secure, since it doesn’t eval() anything.

This removes extra whitespaces from both sides of string and converts two spaces to one within the string. Note that this won’t convert three or more spaces in a row to one! Another way I can suggest is using implode and explode that is safer but totally not optimum!

My suggestion is using a native for loop or using regex to do this kind of job.

To expand on Sandip’s answer, I had a bunch of strings showing up in the logs that were mis-coded in bit.ly. They meant to code just the URL but put a twitter handle and some other stuff after a space. It looked like this

Normally, that would‘t be a problem, but I’m getting a lot of SQL injection attempts, so I redirect anything that isn’t a valid ID to a 404. I used the preg_replace method to make the invalid productID string into a valid productID.

I look for a space in the URL and then remove everything after it.

Источник

Remove all special characters from a string [duplicate]

I am facing an issue with URLs, I want to be able to convert titles that could contain anything and have them stripped of all special characters so they only have letters and numbers and of course I would like to replace spaces with hyphens.

How would this be done? I’ve heard a lot about regular expressions (regex) being used.

3 Answers 3

This should do what you’re looking for:

Will output: abcdef-g

Hey, just a quick question, how can I prevent multiple hyphens from being next to each other? and have them replaced with just 1?

php remove all spaces from string. Смотреть фото php remove all spaces from string. Смотреть картинку php remove all spaces from string. Картинка про php remove all spaces from string. Фото php remove all spaces from string

Update

The solution below has a «SEO friendlier» version:

There were also some common misspellings that seemed to influence the results, and the only explanation that made sense to me is that our URL were being unpacked, the words singled out, and used to drive God knows what ranking algorithms. And those algorithms apparently had been fed with UTF8-cleaned strings, so that «Perù» became «Peru» instead of «Per». «Per» did not match and sort of took it in the neck.

Previous answer

So the finished function along with test cases:

To handle UTF-8 I used a cleanString implementation found online (link broken since, but a stripped down copy with all the not-too-esoteric UTF8 characters is at the beginning of the answer; it’s also easy to add more characters to it if you need) that converts UTF8 characters to normal characters, thus preserving the word «look» as much as possible. It could be simplified and wrapped inside the function here for performance.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *