1

I have a string filled with numbers and i'm trying to add a character to the front of every number series:

$dna = "273385 14093 1522520 1759 277697 283096 1133193 191835 246752 204984 973590"

but I want to end up with:

$dna = "m#273385 m#14093 m#1522520 m#1759 m#277697 m#283096 m#1133193 m#191835 m#246752 m#204984 m#973590"

the closest I've gotten is using

$dna= preg_replace('~(\w+)~', '$1m#',$dna);

which gives me:

$dna = "273385m# 14093m# 1522520m#"

How can I get it to append to the front?

Fight Fire With Fire
  • 1,626
  • 3
  • 19
  • 28

4 Answers4

3

You may use

preg_replace('~\d+~', 'm#$0', $dna)

See the regex demo

The \d+ will match streaks of 1 or more digits and m#$0 will replace each match with m# and the whole match value (referred to with $0 backreference).

See the PHP demo:

$dna = "273385 14093 1522520 1759 277697 283096 1133193 191835 246752 204984 973590";
echo preg_replace('~\d+~', 'm#$0', $dna);
// => m#273385 m#14093 m#1522520 m#1759 m#277697 m#283096 m#1133193 m#191835 m#246752 m#204984 m#973590
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
0

Here is a way not mentioned (non regex)

$dna = "273385 14093 1522520 1759 277697 283096 1133193 191835 246752 204984 973590";
$dna = 'm#'.implode(' m#', explode(' ', $dna));
echo $dna;

Sandbox

This assumes that the string won't be empty, if it is you'll get m# as the result, unless you check first. And, that there are only numbers in the string.

You can fix the first one quite easily.

   $dna = empty($dna) ? '': 'm#'.implode(' m#', explode(' ', $dna));
ArtisticPhoenix
  • 21,464
  • 2
  • 24
  • 38
-1

You may use str_replace to make the change.

$dna = "273385 14093 1522520 1759 277697 283096 1133193 191835 246752 204984 973590";
$dna = 'm#' . str_replace(' ',' m#',$dna);
Dave
  • 5,108
  • 16
  • 30
  • 40
-1

..or the general case? (I'm assuming that the format of the string is groups of digits, separated by one space)

define('DNA_SEPARATOR', ' ');
define('DNA_PREFIX', 'm#');

$dna = "273385 14093 1522520 1759 277697 283096 1133193 191835 246752 204984 973590";
$arr = explode(DNA_SEPARATOR, $dna);

// In case you're not sure it's all groups of digits
// $arr = array_filter($arr, function($v) { return is_numeric($v); });

$arr = array_map(function($v) { return DNA_PREFIX.$v; }, $arr);
$dna = implode(DNA_SEPARATOR, $arr);
Torbjörn Stabo
  • 769
  • 4
  • 7