Replacing multiple parts of a string

£可爱£侵袭症+ 提交于 2019-12-25 03:08:52

问题


Let's say I have the following for example's sake:

$string = "^4Hello World ^5Foo^8Bar";

I'm currently using the following function to replace the carets and adjoining numbers, which is the closest I could get to what I wanted.

function addColours($input) {
    $var = $input;
    $var = str_replace('^0', '</span><span style="color: #000000">', $var);
    $var = str_replace('^1', '</span><span style="color: #ff0000">', $var);
    $var = str_replace('^2', '</span><span style="color: #00ff00">', $var);
    $var = str_replace('^3', '</span><span style="color: #ffff00">', $var);
    $var = str_replace('^4', '</span><span style="color: #0000ff">', $var);
    $var = str_replace('^5', '</span><span style="color: #00ffff">', $var);
    $var = str_replace('^6', '</span><span style="color: #ff00ff">', $var);
    $var = str_replace('^7', '</span><span style="color: #ffffff">', $var);
    $var = str_replace('^8', '</span><span style="color: #CC9933">', $var);
    $var = str_replace('^9', '</span><span style="color: #8D8D8D">', $var);
    return $var;
}

Which would return the following for the string.

</span><span style="color: #0000ff">Hello World </span><span style="color: #00ffff">Foo</span><span style="color: #CC9933">Bar

It works fine for the middle parts of the string, but obviously it's adding an unneeded </span> at the beginning of the string and it isn't closing the end tag.

Is there any way of making this work?

Thanks, Ben.


回答1:


This is what i was talking about in the comments:

$colorMap = array(
  '000000', // 0
  'ff0000', // 1
  '00ff00', // 2...     
);

$template = '<span style="color:#%s">%s</span>';

// split by "^" followed by 0-9
$parts = preg_split('/\^(\d)/', $string, -1,
            PREG_SPLIT_NO_EMPTY + PREG_SPLIT_DELIM_CAPTURE);

$result = '';

// rebuild string (odd elements are delimiters)
foreach($parts as $idx => $part)
  if((($idx % 2) === 0) && isset($colorMap[(int)$part]))
    $result .= sprintf($template, $colorMap[(int)$part], $parts[$idx + 1]);



回答2:


How about this then?

function addColours($input) {
    $out = '';
    $replacements = array(
            '1' => '000000',
            '2' => 'ff0000'
    );

    foreach(explode('^', $input) as $span) {
        if(in_array($span[0], array_keys($replacements))) {
            $out .= '<span style="color: #' .  $replacements[$span[0]] . '">' . substr($span, 1) . '</span>';
        } else {
            $out .= $span;
        }
    }

    return $out;
}

$body = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. ^1Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. ^2It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.";

print addColours($body);



回答3:


You really need to be running a preg replace, not a strreplace. The problem you will still run into here is that you need to find a patter such as '^4Some Sentance ^' so that you can end the span correctly. But what would happen if the entry was the last time a tag was used and it wasn't closed? It would fail.

I recommend switching to this format:

[4]Some sentence[/4]

Then you can run a simple str_replace correctly:

function addColours($input) {
    $replacements = array(
            '1' => '000000',
            '2' => 'ff0000'
    );

    foreach($replacements as $key => $value) {
        $input = str_replace("[$key]", '<span style="color: #' . $value . '">');
        $input = str_replace("[/$key]", '</span>');
    }

    return $input;
}



回答4:


Here's my two cents. It's the closest to the OPs code, and doesn't require manual rebuilding of the string.

function addColours($input) {

  $var = $input;

  $var = preg_replace('/\^0(.*?)((\^\d)|($))/', '<span style="color: #000000">$1</span>$2', $var);
  $var = preg_replace('/\^1(.*?)((\^\d)|($))/', '<span style="color: #ff0000">$1</span>$2', $var);
  $var = preg_replace('/\^2(.*?)((\^\d)|($))/', '<span style="color: #00ff00">$1</span>$2', $var);
  $var = preg_replace('/\^3(.*?)((\^\d)|($))/', '<span style="color: #ffff00">$1</span>$2', $var);
  $var = preg_replace('/\^4(.*?)((\^\d)|($))/', '<span style="color: #0000ff">$1</span>$2', $var);
  $var = preg_replace('/\^5(.*?)((\^\d)|($))/', '<span style="color: #00ffff">$1</span>$2', $var);
  $var = preg_replace('/\^6(.*?)((\^\d)|($))/', '<span style="color: #ff00ff">$1</span>$2', $var);
  $var = preg_replace('/\^7(.*?)((\^\d)|($))/', '<span style="color: #ffffff">$1</span>$2', $var);
  $var = preg_replace('/\^8(.*?)((\^\d)|($))/', '<span style="color: #CC9933">$1</span>$2', $var);
  $var = preg_replace('/\^9(.*?)((\^\d)|($))/', '<span style="color: #8D8D8D">$1</span>$2', $var);

  return $var;

}


来源:https://stackoverflow.com/questions/18833968/replacing-multiple-parts-of-a-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!