Home > Software design >  How to remove a character from a string only if it follows a number?
How to remove a character from a string only if it follows a number?

Time:09-23

I have several rows of data that are in address format, I want to remove the house number from each address.

So far I have been able to remove the number using:

<?php
$string = '25a Test Lane';
if (preg_match("/[0-9]/", $string)) {
  $string = preg_replace("/[0-9]/", "", $string);
}
?>

$string then becomes 'a Test Lane' - but how would I go about removing 'a' as well? Bearing in mind the 'a' could be any letter following a number. I'd want to remove any character that immediately follows the number (no space in between).

CodePudding user response:

You can use

trim(preg_replace("/\b\d [a-zA-Z]*\b/", "", $string))
trim(preg_replace("/\b\d [a-zA-Z]?\b/", "", $string))

Here is the regex demo. NOTE: if you only want to allow a single letter after the number, replace * with ? in [a-zA-Z]*.

Details:

  • \b - a word boundary
  • \d - one or more digits
  • [a-zA-Z]* - zero or more ASCII letters
  • [a-zA-Z]? - one or zero ASCII letters
  • \b - a word boundary.

See the PHP demo:

$string = '25a Test Lane';
$string = trim(preg_replace("/\b\d [a-zA-Z]*\b/", "", $string));
echo $string;
// => Test Lane
  • Related