1

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).

2
  • In this case, simply adding a character group for letters a-z with the ? quantifier should probably do the job, /[0-9]+[a-z]?/
    – CBroe
    Sep 23, 2021 at 11:27
  • What result do you expect? '25 Test Lane' or ' Test Lane' ?
    – jspit
    Sep 23, 2021 at 11:44

1 Answer 1

1

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
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.