Regex Expression Help Please

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
User avatar
Benjamin
Site Administrator
Posts: 6935
Joined: Sun May 19, 2002 10:24 pm

Regex Expression Help Please

Post by Benjamin »

I have this text...
said" here are some words!" I
Here is my Regex

Code: Select all

$NewText = preg_replace('/[\s]*"[\s]*(.+)[\s]*"[\s]*/', " \"$1\" ", $NewText);
Here is the output, which is wrong because there are 2 spaces after the !.
said "here are some words! " I
And the output should be..
said "here are some words!" I
User avatar
s.dot
Tranquility In Moderation
Posts: 5001
Joined: Sun Feb 06, 2005 7:18 pm
Location: Indiana

Post by s.dot »

After trying your regex (PHP 5.1.2) I get the following output:

Code: Select all

said "here are some words!" I
Looks good to me? No spaces after the !.

The only thing I can suggest is if you are replacing the text in the right variable
You have $NewText = preg_replace(.....,$NewText);
Which is perfectly legal, just seing if you meant to do that?
Set Search Time - A google chrome extension. When you search only results from the past year (or set time period) are displayed. Helps tremendously when using new technologies to avoid outdated results.
User avatar
Benjamin
Site Administrator
Posts: 6935
Joined: Sun May 19, 2002 10:24 pm

Post by Benjamin »

Hmm, yeah I am reusing the variable name on purpose.

It does work with () but not ""

I am using 5.0.4

Here is more code...

Code: Select all

$NewText = str_replace("\n  ", "\n", $NewText);  // removes 2 spaces after line feeds
  $NewText = preg_replace('/,(\w+)/', ", $1", $NewText);  // inserts a space after commas if there isn't one
  $NewText = preg_replace('/[\s]*"[\s]*(.+)[\s]*"[\s]*/', " \"$1\" ", $NewText);  // formats qouted text
  $NewText = preg_replace('/[\s]*\([\s]*(.+)[\s]*\)[\s]*/', " ($1) ", $NewText);  // formats parentheses
  $NewText = preg_replace('/\s*,/', ",$1", $NewText);  // removes whitespace before commas
Post Reply