• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 583
  • Last Modified:

ereg_replace convert to preg_replace



… because of the deprecation of ereg_replace, are these conversions adequate? How can they be improved?


regards,

GJ

From:
ereg_replace("-+", "-", $Str); // remove multiple hyphens
ereg_replace(" +", " ", $Str); // remove multiple spaces

to:
preg_replace("-+", "-", $Str); // remove multiple hyphens
preg_replace(" +", " ", $Str); // remove multiple spaces

Open in new window

0
ggjones
Asked:
ggjones
  • 4
  • 2
2 Solutions
 
Ray PaseurCommented:
Quite often, ereg-to-preg conversions are as easy as adding a regex delimiter.

Examples in code snippet.
preg_replace("/\-+/", "-", $Str); // remove multiple hyphens
preg_replace("/ +/", " ", $Str); // remove multiple spaces

Open in new window

0
 
Ray PaseurCommented:
Note that the dash is a metacharacter and needs to be escaped with the backslash or through the use of preg_quote.

eregi() is the case-insensitive function.  It is implemented by adding the letter "i" to the end of the regex after the last regex delimiter.
0
 
ggjonesAuthor Commented:

... thanks Ray...  I'm having some syntax problems extrapolating from this.


Essentially, this is part of a function that will manage odd chars (-,./) etc

any ideas to get the $char var to work, as part of the pattern?

cheers,

GJ

.
$char = '-';

preg_replace("'/\' . $char . '+/'", $char, $str)

Open in new window

0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
Ray PaseurCommented:
Sure.  Construct the regex string in separate pieces, using string concatenation like this...  
See http://us2.php.net/manual/en/function.preg-quote.php

You might enjoy this article which is not really about regular expressions, so much as how to write and debug code.  It just uses regular expressions for the test case.
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_7830-A-Quick-Tour-of-Test-Driven-Development.html

Best regards, ~Ray


$regex
= '#'               // REGEX DELIMITER
. preg_quote($char) // ESCAPED MATCH STRING
. '#'               // REGEX DELIMITER
. 'i'               // CASE-INSENSITIVE
;
$new = preg_replace($regex, $char, $string);

Open in new window

0
 
ggjonesAuthor Commented:
... thanks Ray, that does the trick. Awesome.

GJ

.
0
 
Ray PaseurCommented:
Thanks for the points -- it's a really great question and one that those of us with legacy code, well, we are going to have to come to grips with it!  All the best, ~Ray
0

Featured Post

Become an Android App Developer

Ready to kick start your career in 2018? Learn how to build an Android app in January’s Course of the Month and open the door to new opportunities.

  • 4
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now