473,732 Members | 2,207 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Ignore or remove whitespace in a string

Which is the simplest way to remove all whitespace from a string? Is there a
simpler method than a regex replace?
Or how can I tell a regex pattern to ignore all whitespace in my subject
string? There is a global modifier to ignore all spaces in the pattern, but
I couldn't find one for ignoring spaces in the subject string. Do I really
have to either do a preg_replace to remove all whitespace or stick a lot of
\s* into my search pattern?

Greetings,
Thomas
Jul 16 '05 #1
9 90014
Thomas Mlynarczyk wrote:
Which is the simplest way to remove all whitespace from a string? Is there
a simpler method than a regex replace?
Or how can I tell a regex pattern to ignore all whitespace in my subject
string? There is a global modifier to ignore all spaces in the pattern,
but I couldn't find one for ignoring spaces in the subject string. Do I
really have to either do a preg_replace to remove all whitespace or stick
a lot of \s* into my search pattern?

Greetings,
Thomas


PS....

$nospaces = str_replace(' ', '', $input);

will strip spaces; if you want to take out carriage returns, newlines, etc
you'll need
str_replace("\n ", ''
str_replace("\r ", ''

etc
Jul 16 '05 #2
In article <bg************ *@news.t-online.com>,
"Thomas Mlynarczyk" <bl************ *@hotmail.com> wrote:
Which is the simplest way to remove all whitespace from a string?
*All whitespace*, not just space character?

$after=preg_rep lace('/\s+/','',$before);

(Or the ereg equivalent would be [[:space:]].)
Is there a simpler method than a regex replace?
Assuming the above, and that your PHP does have PCRE support compiled in,
not really. Any particular reason why want to avoid a regex? PCRE is very
fast and (in this case) very simple.
Or how can I tell a regex pattern to ignore all whitespace in my subject
string?
Well, it's possible to tell PCRE to "find X except where it comes
before/after Y", if that's what you mean... It would help if you
elaborated on what specifically you want to accomplish.
There is a global modifier to ignore all spaces in the pattern, but I
couldn't find one for ignoring spaces in the subject string. Do I really
have to either do a preg_replace to remove all whitespace or stick a lot
of \s* into my search pattern?


It depends on what you need to match. Sometimes when PCRE newbies are
tempted to use a lot of \s* they're attempting to workarounds problems for
which PCRE already has more graceful solutions. For instance, ungreedy
matching is often what they need. Or word boundary matching. Or just a
carefully-placed ".*". Etc. If you explain what you want to do, there
may well be non-kludge solution which we can suggest to you.

--
CC
Jul 16 '05 #3
Also sprach CC Zona:
Which is the simplest way to remove all whitespace from a string?
*All whitespace*, not just space character?
$after=preg_rep lace('/\s+/','',$before);
Would it make a difference if it was just the space character? (I mean would
there be a non-regex solution in that case?)
Is there a simpler method than a regex replace? Assuming the above, and that your PHP does have PCRE support compiled
in, not really. Any particular reason why want to avoid a regex?
Given the possibilities of regex's, they probably use up a lot of either
system ressources or processing time (or both), so one should not use them
when there are other possible solutions.
PCRE is very fast and (in this case) very simple.


Does this mean system ressources and processing time are not an issue here?
Or how can I tell a regex pattern to ignore all whitespace in my
subject string?


Well, it's possible to tell PCRE to "find X except where it comes
before/after Y", if that's what you mean... It would help if you
elaborated on what specifically you want to accomplish.


Basically, I want to parse a string and for the sake of better readability I
want to allow whitespace, just like "$var=1;" and " $var = 1; ". But for
parsing it's easier when there is no whitespace or when the parsing regex
can just ignore it.
Jul 16 '05 #4
Also sprach matty:
Which is the simplest way to remove all whitespace from a string? Is
there a simpler method than a regex replace?
Or how can I tell a regex pattern to ignore all whitespace in my
subject string? There is a global modifier to ignore all spaces in
the pattern, but I couldn't find one for ignoring spaces in the
subject string. Do I really have to either do a preg_replace to
remove all whitespace or stick a lot of \s* into my search pattern?
Depends what you want to match/replace - what are you doing with it?


The whitespace is just there for better readability, but should have no
impact whatsoever on the parsing of the string as it doesn't have any
"meaning".

Jul 16 '05 #5
Also sprach matty:
$nospaces = str_replace(' ', '', $input);

will strip spaces; if you want to take out carriage returns,
newlines, etc you'll need
str_replace("\n ", ''
str_replace("\r ", ''


Thanks for this hint, but I was hoping there could be something like trim(),
but working on spaces in the middle of the string as well. So str_replace()
is already the most simple thing to do in my case?

Jul 16 '05 #6
Thomas Mlynarczyk wrote:
Also sprach CC Zona:
Which is the simplest way to remove all whitespace from a string?
*All whitespace*, not just space character?
$after=preg_rep lace('/\s+/','',$before);


Would it make a difference if it was just the space character? (I mean
would there be a non-regex solution in that case?)
Is there a simpler method than a regex replace?
Assuming the above, and that your PHP does have PCRE support compiled
in, not really. Any particular reason why want to avoid a regex?


Given the possibilities of regex's, they probably use up a lot of either
system ressources or processing time (or both), so one should not use them
when there are other possible solutions.
PCRE is very fast and (in this case) very simple.


Does this mean system ressources and processing time are not an issue
here?
Or how can I tell a regex pattern to ignore all whitespace in my
subject string?


Well, it's possible to tell PCRE to "find X except where it comes
before/after Y", if that's what you mean... It would help if you
elaborated on what specifically you want to accomplish.


Basically, I want to parse a string and for the sake of better readability
I
want to allow whitespace, just like "$var=1;" and " $var = 1; ". But for
parsing it's easier when there is no whitespace or when the parsing regex
can just ignore it.

preg_match_all( '/(\$[^ =]+)\s*\=\s*([^;]+);/', $input, $matches); should do
what you want; the pcre stuff is pretty good, and if you'd be doing a str_replace
first, you're better off just matching the values out

--
Matt Mitchell - AskMeNoQuestion s
Dynamic Website Development and Marketing
Jul 16 '05 #7
In article <bg************ *@news.t-online.com>,
"Thomas Mlynarczyk" <bl************ *@hotmail.com> wrote:
*All whitespace*, not just space character?
$after=preg_rep lace('/\s+/','',$before);
Would it make a difference if it was just the space character? (I mean would
there be a non-regex solution in that case?)


str_replace. If you really are that adamently opposed to using regex, you
certainly could use a series of str_replace operations to remove all
whitespace characters. (But since processing time

to be your concern, benchmark it because I suspect that approach would
actually take more time than a single preg_replace.)
PCRE is very fast and (in this case) very simple.


Does this mean system ressources and processing time are not an issue here?


For a single preg_replace of whitespace? That is absolutely trivial. If
that is your reason for avoiding regex, don't bother. For something like
this, it's your programming resources/time that are invaluable: a single
operation is quick to write, easy to read/debug/change, etc. When you're
doing multiple capturing expressions against large arrays, then it's worth
spending some of your time to optimize; for this, no.
Basically, I want to parse a string and for the sake of better readability I
want to allow whitespace, just like "$var=1;" and " $var = 1; ".


For example...?

--
CC
Jul 16 '05 #8
CC Zona:
In article <bg************ *@news.t-online.com>,
"Thomas Mlynarczyk" <bl************ *@hotmail.com> wrote:
> *All whitespace*, not just space character?
> $after=preg_rep lace('/\s+/','',$before);


Would it make a difference if it was just the space character? (I mean
would there be a non-regex solution in that case?)


str_replace. If you really are that adamently opposed to using regex, you
certainly could use a series of str_replace operations to remove all
whitespace characters. (But since processing time
to be your concern, benchmark it because I suspect that approach would
actually take more time than a single preg_replace.)


Which is faster I don't know, but you only need one call to str_replace,
e.g.:
str_replace(arr ay("\n", "\r", "\t", " "), '', $str);

André Næss
Jul 16 '05 #9
Thomas Mlynarczyk:
Also sprach André Næss:
Which is faster I don't know, but you only need one call to
str_replace, e.g.:
str_replace(arr ay("\n", "\r", "\t", " "), '', $str);


Wow - *that* would work? I didn't know you could pass an array to
str_replace. But would it "perform" significantly better than a set of
several separate str_replace() calls?


No idea, you can always benchmark it though. If the performance difference
between using regex, several str_replace or one str_replace matters to your
application, you probably shouldn't be doing that particular part in PHP
anyway...

In cases where str_replace is sufficient I prefer it. When people see
regular expression it's probably easy to think "Something complicated is
happening here", whereas with str_replace it's very straightforward .

But most scripters are fairly good at regular expressions, so it's not
really a very strong argument.

André Næss
Jul 16 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
8475
by: Purdy | last post by:
I have an asp.net application. i export to excel, in exporting to excel i use an xslt to define the columns and look. on one of the fields i need the word 'qty' but i need it to look like ' qty' with 5 white spaces. i am able to do that in my xslt and the export to Excel looks fine also. but then i have another app i feed this excel sheet to, and in that
3
21528
by: soni29 | last post by:
hi, how can i remove a string from an existing string in javascript. i have a textbox in a form and want to make sure that when the user clicks a button that certain words are moved, like all instances of "hello" should be taken out of the text the user typed in the textbox. any ideas? thank you.
6
2512
by: shallow | last post by:
Hi all, msaccess (2003) seems to be unable to cope with whitespace strings: let's assume a table with a text field as primary key. now enter a new record that has a number of spaces and only spaces in the primary key field. msaccess will complain and claim "index or primary key cannot contain
0
3349
by: threecrans | last post by:
If you create a new server control, and override the Render method with the following code: protected override void Render(HtmlTextWriter output) { // <TABLE id="mytable"> output.AddAttribute(HtmlTextWriterAttribute.Id, "mytable"); output.RenderBeginTag(HtmlTextWriterTag.Table); // <TR>
10
60485
by: teenIce | last post by:
Hi all, Does anyone have suggestion what can I do to remove some string from a string? Like this : Original : I have a cat. Remove : have Result : I a cat. Thanks in advance.
4
4333
by: howa | last post by:
Consider an example: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <style> a { background-color:red;} </style> </head>
36
9176
by: laredotornado | last post by:
Hi, I'm using PHP 5. I have an array of strings. What is the simplest way to remove the elements that are empty, i.e. where the expression "empty($elt)" returns true? Thanks, - Dave
5
4716
by: ziycon | last post by:
I have the below code and I'm working how I would go about getting it to align at the left and remove all the white space while keeping the formatting/indenting in place? Edit: Its all contained in a PHP variable and once all is generated its echoed to screen. <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html...
0
8946
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8774
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9447
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9307
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9235
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9181
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6735
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6031
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4809
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.