开发者

How to do such string manipulations in PHP?

开发者 https://www.devze.com 2023-02-15 06:32 出处:网络
I need to convert \"01,02,03,04,05,07:01\" to: <b>07</b><b>09</b><b>30</b><b class开发者_如何学运维=\"color_blue_ball\">11</b>

I need to convert

 "01,02,03,04,05,07:01"

to:

<b>07</b><b>09</b><b>30</b><b class开发者_如何学运维="color_blue_ball">11</b>

That is ,wrap those before : with <b></b> ,but those after : with <b class="color_blue_ball"></b>.If there's no :,all should be wrapped with <b></b>

Anyone knows how to do this?


No need for regex:

echo '<b>' . str_replace(array(',', ':'), array('</b><b>', '</b><b class="color_blue_ball">'),  "01,02,03,04,05,07:01") . '</b>';

Edit: if the "01,02,03,04,05,07:01,04,06" is valid, then the idea the same but explode is added:

$parts = explode(':', "01,02,03,04,05,07,01,04:06");
echo '<b>' . str_replace(',', '</b><b>', $parts[0]) . (isset($parts[1]) ? str_replace(',', '</b><b class="color_blue_ball">',  ',' . $parts[1]) : '') . '</b>';


A tad more verbose:

<?php
function wrapValues($array, $wrapper) {
  $result = array();
  foreach ($array as $elem) {
    $result []= str_replace('?', $elem, $wrapper);
  }   
  return implode('', $result);
}

$values = "01,02,03,04,05,07:01,02";
$firstWrapper = '<b>?</b>';
$secondWrapper = '<b class="color_blue_ball">?</b>';

list($first, $second) = explode(':', $values);

echo wrapValues(explode(',', $first), $firstWrapper) . 
     wrapValues(explode(',', $second), $secondWrapper);


I don't know if it's the best way to do it, but I would probably split the string on the :, then on ,, and then deal with each part separately and join them back together.

0

精彩评论

暂无评论...
验证码 换一张
取 消