Formatting string according to pattern without regex in php -


how can format arbitrary string according flexible pattern? solution came using regular expressions, need 2 "patterns" (one search , 1 output).

example:

$str = '123abc5678";  

desired output: 12.3ab-c5-67.8

i use pattern in variable (one user can define without knowledge of regular expressions) this:

$pattern = '%%.%%%-%%-%%.%'; 

so user have use 2 different characters (% , .)

a solution regex this:

$str = '123abc5678'; $pattern_src = '@(.{2})(.{3})(.{2})(.{2})(.{1})@'; $pattern_rpl = "$1.$2-$3-$4.$5";  $res = preg_replace($pattern_src, $pattern_rpl, $str); //$res eq 12.3ab-c5-67.8 

way complicated since user need define $pattern_src , $pattern_rpl. if string vary in length, more complex explain.

yes, write function/parser builds required regular expressions based on simple user pattern %%.%%%-%%-%%.%. wonder if there "built in" way achieve php? thinking sprintf etc., doesn't seem trick. ideas?

i thinking sprintf etc., doesn't seem trick.

you're on right track. can accomplish vsprintf follows:

$str = '123abc5678'; $pattern = '%%.%%%-%%-%%.%'; echo vsprintf(str_replace('%', '%s', $pattern), str_split($str)); 

output:

12.3ab-c5-67.8

this assuming number of % characters in $pattern match length of $str.


Comments

Popular posts from this blog

javascript - Uncaught FirebaseError: Messaging: This method is available in a Window context -

c# - How to clear picker if It is selected in xamarin forms? -

angular - File Name and Extension not respected when sent from .NET Web API to Angular2 App -