php delete space in string

Php delete space in 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 delete space in string. Смотреть фото php delete space in string. Смотреть картинку php delete space in string. Картинка про php delete space in string. Фото php delete space in 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 delete space in string. Смотреть фото php delete space in string. Смотреть картинку php delete space in string. Картинка про php delete space in string. Фото php delete space in string

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

php delete space in string. Смотреть фото php delete space in string. Смотреть картинку php delete space in string. Картинка про php delete space in string. Фото php delete space in string

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

php delete space in string. Смотреть фото php delete space in string. Смотреть картинку php delete space in string. Картинка про php delete space in string. Фото php delete space in 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 delete space in string. Смотреть фото php delete space in string. Смотреть картинку php delete space in string. Картинка про php delete space in string. Фото php delete space in string

php delete space in string. Смотреть фото php delete space in string. Смотреть картинку php delete space in string. Картинка про php delete space in string. Фото php delete space in 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.

Источник

How can strip whitespaces in PHP’s variable?

I know this comment PHP.net. I would like to have a similar tool like tr for PHP such that I can run simply

I run unsuccessfully the function php_strip_whitespace by

I run the regex function also unsuccessfully

php delete space in string. Смотреть фото php delete space in string. Смотреть картинку php delete space in string. Картинка про php delete space in string. Фото php delete space in string

15 Answers 15

To strip any whitespace, you can use a regular expression

See also this answer for something which can handle whitespace in UTF-8 strings.

A regular expression does not account for UTF-8 characters by default. The \s meta-character only accounts for the original latin set. Therefore, the following command only removes tabs, spaces, carriage returns and new lines

With UTF-8 becoming mainstream this expression will more frequently fail/halt when it reaches the new utf-8 characters, leaving white spaces behind that the \s cannot account for.

To deal with the new types of white spaces introduced in unicode/utf-8, a more extensive string is required to match and removed modern white space.

Because regular expressions by default do not recognize multi-byte characters, only a delimited meta string can be used to identify them, to prevent the byte segments from being alters in other utf-8 characters ( \x80 in the quad set could replace all \x80 sub-bytes in smart quotes)

This accounts for and removes tabs, newlines, vertical tabs, formfeeds, carriage returns, spaces, and additionally from here:

nextline, non-breaking spaces, mongolian vowel separator, [en quad, em quad, en space, em space, three-per-em space, four-per-em space, six-per-em space, figure space, punctuation space, thin space, hair space, zero width space, zero width non-joiner, zero width joiner], line separator, paragraph separator, narrow no-break space, medium mathematical space, word joiner, ideographical space, and the zero width non-breaking space.

Many of these wreak havoc in xml files when exported from automated tools or sites which foul up text searches, recognition, and can be pasted invisibly into PHP source code which causes the parser to jump to next command (paragraph and line separators) which causes lines of code to be skipped resulting in intermittent, unexplained errors that we have begun referring to as «textually transmitted diseases»

[Its not safe to copy and paste from the web anymore. Use a character scanner to protect your code. lol]

Источник

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 delete space in string. Смотреть фото php delete space in string. Смотреть картинку php delete space in string. Картинка про php delete space in string. Фото php delete space in 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.

Источник

Many times, the strings have extra spaces that need to be removed. For example, you might want to replace multiple spaces with a single space or you might want to get rid of all the whitespace in a string. Similarly, you might be planning on stripping all the whitespace from either the left or the right end of a string.

Remove whitespace from the beginning or end of a String

If you want to remove whitespace only from the beginning of a string, you should use the ltrim() function in PHP. If you want to remove whitespace only from the end of a string, you should use the rtrim() function in PHP. If you want to remove whitespace from both ends of a string, you should use the trim() function instead of using both ltrim() and rtrim().

These functions will remove the following whitespace characters:

Remove all the whitespace in a String

Some times, the strings you are working with will have unwanted whitespace in the middle and in the beginning as well as in the end. The trimming function will be ineffective against it.

If you just want to remove all the whitespace characters irrespective of where they occur in the string, you should use str_replace() to replace all their occurrences with a blank string.

The whitespace can consist of more than just space characters. In such cases, using the str_replace() function won’t cut it. The special \s character in a regular expression is used to represent all whitespace characters that you removed by trim(), ltrim() and rtrim().

Replace multiple whitespace characters with a single space

Most of the times when you decide to remove extra whitespace characters from a string, you would want to replace two or more of them with a single space character. This is different than removing all the spaces so you will have to make small changes in the regular expression and the preg_replace() function.

In the above example, the + after \s means that you want to replace one or more whitespace characters with a single space. The only problem now is that the main string might contain multiple whitespace characters at both ends. In such cases, there will be one space character present on both sides even after using preg_replace(). The solution here is to use trim() on the resulting string.

Источник

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

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