PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, November 20, 2022

[FIXED] How to remove a character from a string only if it follows a number?

 November 20, 2022     php, preg-replace     No comments   

Issue

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


Solution

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


Answered By - Wiktor Stribiżew
Answer Checked By - Senaida (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing