Php space character in string

How to add extra whitespace in PHP?

I was wondering how can I add extra whitespace in php is it something like \s please help thanks. Is there a tutorial that list these kind of things thanks.

We need more information about what you’re trying to do. Do you want whitespace rendered on the web page?

Do you mean vertical or horizontal whitespace? Space inside a string, or space between two elements on the rendered page?

this is not a php question, this is an html question because php outputs all spaces but web browsers ignore extra whitespaces

@Tobia: This is not necessary an HTML question. Maybe the OP ask for an explicit way to add whitespaces in a string other than the usual whitespace character. This can be useful in order to make them more visible. The linefeed character \n is a another example. Typing a simple newline character (by hitting the Return key) works, but using the linefeed escaped character is more explicit !

14 Answers 14

 str_repeat(' ', 5); // adds 5 spaces 

To render more than one whitespace on most web browsers use   instead of normal white spaces.

echo "

Hello     punt"; // This will render as Hello Punt (with 4 white spaces) echo "

Hello punt"; // This will render as Hello punt (with one space)

For showing data in raw format (with exact number of spaces and «enters») use HTML tag.

echo "
Hello punt

"; //Will render exactly as written here (8 white spaces)

Or you can use some CSS to style current block, not to break text or strip spaces (I don’t know, but this one)

Any way you do the output will be the same but the browser itself strips double white spaces and renders as one.

PHP (typically) generates HTML output for a web-site.

When displaying HTML, the browser (typically) collapses all whitespace in text into a single space. Sometimes, between tags, it even collapses whitespace to nothing.

In order to persuade the browser to display whitespace, you need to include special tags like   or
in your HTML to add non-breaking whitespace or new lines, respectively.

for adding space character you can use

use this one. it will provide 60 spaces. that is your second parameter.

Use str_pad function. It is very easy to use. One example is below:

The example in this answer is incorrect — there should only be 5 spaces after the word ‘Alien’. The second argument to str_pad is the max number of characters, not the number of times the padding character will be repeated.

The question does not ask to put exact number space after any word 😀 😀 Sometimes you need to put extra space to fill up string length.

Sabbir, you are correct, but that is not my point. In your example you state that echo str_pad($input, 10); will result in the following output: «Alien » (with 10 spaces) But in fact it will output: «Alien » (with 5 spaces) That was my only point, that the sample output is incorrect — that the «10» used in the function call specifies the total characters output (which will include the $input argument), and not the number of spaces to append after the $input. I would have just directly edited the example to fix it, but SO does not allow such small edits.

Источник

If string only contains spaces?

@caw Best answer! The question asked for a way to detect if a string only contains spaces, most answers check if string only contain whitespace character(s).

11 Answers 11

or if you don’t want to include empty strings,

if (strlen($str) > 0 && strlen(trim($str)) == 0) 

@voyager: that would determine if the string had any leading or trailing spaces, the question is does it have only spaces.

@voyager: What about » hello world » ? In that case strlen(trim($str)) is 11 and strlen($str) is 15, but the string is not only made up on spaces.

Point taken, but it would have to be if ((strlen(trim($str)) != strlen($str)) && (strlen(trim($str)) == 0)) if you want to make sure that the string contains only whitespace, but it’s not an empty string.

@voyger: that’s still overkill. do if (strlen($str)>0 && strlen(trim($str))==0) if that’s what you want. or use !empty($str) . why would you bother comparing it to the trimmed string?

If you want to upvote, do it on the other answer, not this one!

This will be the fastest way:

Returns false on empty string because empty is not white-space. If you need to include an empty string, you can add || $str == » This will still result in faster execution than regex or trim.

function stringIsNullOrWhitespace($text)

@stereofrog: I respectfully disagree. Regexes are overkill for something like this, that can be handled perfectly by built in functions.

That’s true, and also maybe builtin functions like shown by John are faster than regexp. But I love regexp, and I use to do everything I can by them, even if not necessary at all. And anyway, I was sure that simplest solutions will have been posted, I just want people not to forget regexp 😀

Источник

Matching a space in regex

How can I match a space character in a PHP regular expression? I mean like «gavin schulz», the space in between the two words. I am using a regular expression to make sure that I only allow letters, number and a space. But I’m not sure how to find the space. This is what I have right now:

$newtag = preg_replace("/[^a-zA-Z0-9s|]/", "", $tag); 

10 Answers 10

If you’re looking for a space, that would be » » (one space).

If you’re looking for one or more, it’s » *» (that’s two spaces and an asterisk) or » +» (one space and a plus).

If you’re looking for common spacing, use «[ X]» or «[ X][ X]*» or «[ X]+» where X is the physical tab character (and each is preceded by a single space in all those examples).

These will work in every* regex engine I’ve ever seen (some of which don’t even have the one-or-more «+» character, ugh).

If you know you’ll be using one of the more modern regex engines, «\s» and its variations are the way to go. In addition, I believe word boundaries match start and end of lines as well, important when you’re looking for words that may appear without preceding or following spaces.

For PHP specifically, this page may help.

From your edit, it appears you want to remove all non valid characters The start of this is (note the space inside the regex):

$newtag = preg_replace ("/[^a-zA-Z0-9 ]/", "", $tag); # ^ space here 

If you also want trickery to ensure there’s only one space between each word and none at the start or end, that’s a little more complicated (and probably another question) but the basic idea would be:

$newtag = preg_replace ("/ +/", " ", $tag); # convert all multispaces to space $newtag = preg_replace ("/^ /", "", $tag); # remove space from start $newtag = preg_replace ("/ $/", "", $tag); # and end 

Источник

PHP check if string contains space between words (not at beginning or end)

I need to check if a string contains a space between words, but not at beginning or end. Let’s say there are these strings:

1: "how r u "; 2: "how r u"; 3: " howru"; 

@heximal not really, you can just check if last and first character is a space and if not then check for space in whole string

3 Answers 3

You can verify that the trimmed string is equal to the original string and then use strpos or str_contains to find a space.

// PHP < 8 if ($str == trim($str) && strpos($str, ' ') !== false) < echo 'has spaces, but not at beginning or end'; >// PHP 8+ if ($str == trim($str) && str_contains($str, ' '))

Some more info if you’re interested

If you use strpos() , in this case, you don’t have to use the strict comparison to false that’s usually necessary when checking for a substring that way. That comparison is usually needed because if the string starts with the substring, strpos() will return 0 , which evaluates as false .

Here it is impossible for strpos() to return 0 , because the initial comparison
$str == trim($str) eliminates the possibility that the string starts with a space, so you can also use this if you like:

if ($str == trim($str) && strpos($str, ' ')) < . 

If you want to use a regular expression, you can use this to check specifically for space characters:

Or this to check for any whitespace characters:

I did some simple testing (just timing repeated execution of this code fragment) and the trim/strpos solution was about twice as fast as the preg_match solution, but I'm no regex master, so it's certainly possible that the expression could be optimized to improve the performance.

Источник

PHP - make sure string has no whitespace

This solution is for the inverse problem: to know if a string contains at least one word.

/** * Check if a string contains at least one word. * * @param string $input_string * @return boolean * true if there is at least one word, false otherwise. */ function contains_at_least_one_word($input_string) < foreach (explode(' ', $input_string) as $word) < if (!empty($word)) < return true; >> return false; > 

If the function return false there are no words in the $input_string. So, you can do something like that:

if (!contains_at_least_one_word($my_string))
if(strlen(trim($username)) == strlen($username)) < // some white spaces are there. >

Surely this won't check for whitespace that is inside $username ? For example, trim(" stack overflow user ") produces "stack overflow user" , which clearly still has whitespace in it.

if (count(explode(' ', $username)) > 1) < // some white spaces are there. >
if ( preg_match('/\s/',$string) ) < echo "yes $string contain whitespace"; >else
$string = "This string have whitespace"; if( $string !== str_replace(' ','',$string) )< //Have whitespace >else < //dont have whitespace >

I've found another good function which is working fine for searching some charsets in a string - strpbrk

if (strpbrk($string, ' ') !== false) < echo "Contain space"; >else

PHP provides a built-in function ctype_space( string $text ) to check for whitespace characters. However, ctype_space() checks if every character of the string creates a whitespace. In your case, you could make a function similar to the following to check if a string has whitespace characters.

/** * Checks string for whitespace characters. * * @param string $text * The string to test. * @return bool * TRUE if any character creates some sort of whitespace; otherwise, FALSE. */ function hasWhitespace( $text )

This question is in a collective: a subcommunity defined by tags with relevant content and experts.

Источник

Читайте также:  Enterprise applications using java
Оцените статью