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

Sunday, November 20, 2022

[FIXED] How to replace in PHP all matches of a digit plus a space with comma in a string

 November 20, 2022     php, preg-replace, regex, replace, string     No comments   

Issue

$str = "Hello 1234567 Stack 56789 Overflow 12345";

$str = preg_replace('/([0-9] )/', ',', $str);

I want this "Hello 1234567, Stack 56789, Overflow 12345,..."


Solution

Use

preg_replace('/\d(?=\s)/', '$0,', $str)

See proof.

Expression explanation

--------------------------------------------------------------------------------
  \d                       digits (0-9)
--------------------------------------------------------------------------------
  (?=                      look ahead to see if there is:
--------------------------------------------------------------------------------
    \s                       whitespace (\n, \r, \t, \f, and " ")
--------------------------------------------------------------------------------
  )                        end of look-ahead


Answered By - Ryszard Czech
Answer Checked By - Mary Flores (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