Home php preg_replace replace the characters in the line, and leave the numbers

preg_replace replace the characters in the line, and leave the numbers

Author

Date

Category

There is a string in PHP Suppose $ STR = ‘Z1.Z2.Z3.Z6’
How to bring it to this species ‘[F1] [F2] [F3] [F6]’ via regular using preg_replace ???
That is, everywhere replacing Z on F, but the corresponding numbers leave and conclude an expression in square brackets.


Answer 1, Authority 100%

$ str = 'z1.z2.z3.z6';
Echo preg_replace ('/ z (\ d +) (. | $) / i', '[F $ {1}]', $ STR);

Answer 2, Authority 50%

Another option

$ string = 'z1.z2.z3.z6';
$ SYMBOL = 'F'; // symbol for replacement
$ PATTERN = ['~ \ W (\ d) ~', '~ (? & lt; = ^ | \.) ~', '~ (? = \. | $) ~', '~ \. ~'] ;
$ replace = [$ symbol. '$ 1', '[', ']', ''];
Echo Preg_replace ($ Pattern, $ Replace, $ String);
// Result: [F1] [F2] [F3] [F6]

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions