字符串中的下标数字

时间:2015-10-06 12:07:50

标签: php regex subscript

我想从字符串中下标每个数字。

例如:

$str = '1Department of Chemistry, College of 2Education for Pure Science';

我想要的输出:

<sub>1</sub>Department of Chemistry, College of <sub>2<sub>Education for Pure Science

我从字符串中获取所有数字:

//digits from string 
preg_match_all('!\d+!', $str, $matches);
print_r($matches);

但是如何将下标效果应用于数字和打印字符串?

5 个答案:

答案 0 :(得分:5)

您可以使用preg_replace

preg_replace( '!\d+!', '<sub>$0</sub>', $str );

Demo

答案 1 :(得分:1)

这可能有所帮助:

$str = '1Department of Chemistry, College of 2Education for Pure Science';
preg_match_all('!\d+!', $str, $matches);
foreach($matches[0] as $no){
    $str = str_replace($no, '<sub>'.$no.'</sub>', $str);
}
echo htmlentities($str);

会给出输出:

<sub>1</sub>Department of Chemistry, College of <sub>2</sub>Education for Pure Science

preg_replace会提供相同的输出:

$str = '1Department of Chemistry, College of 2Education for Pure Science';
$str = preg_replace( '!\d+!', '<sub>$0</sub>', $str );
echo htmlentities($str);

答案 2 :(得分:1)

我假设你想要这样的东西

$string = '1Department of Chemistry, College of 2Education for Pure Science';
$pattern = '/(\d+)/';
$replacement = '<sub>${1}</sub>';
echo preg_replace($pattern, $replacement, $string);

找到的号码将在子标签内被替换为自身。这个例子来自于preg-replace的PHP手册,你可以在这里找到http://php.net/manual/en/function.preg-replace.php

答案 3 :(得分:0)

<?php

function subscript($string)
{
    return preg_replace('/(\d+)/', '<sub>\\1</sub>', $string);
}

$input    = '1Department of Chemistry, College of 2Education for Pure Science';
$expected = '<sub>1</sub>Department of Chemistry, College of <sub>2</sub>Education for Pure Science';
$output   = subscript($input);

if ($output === $expected) {
    printf('It works! %s', htmlentities($output));
} else {
    printf('It does not work! %s', htmlentities($output));
}

答案 4 :(得分:0)

我已经知道你已经接受了答案,但我仍然在发布这个答案,因为我已经开始工作了,第二个可能是这对其他人来说可能会有所帮助。

<?php

$str = '1Department of Chemistry, College of 2Education for Pure Science';

$strlen = strlen( $str );
$numbers = array();
$replace = array();
for( $i = 0; $i <= $strlen; $i++ ) {
    $char = substr( $str, $i, 1 );
    // $char contains the current character, so do your processing here
    if(is_numeric($char)){
        $numbers[] = $char;
        $replace[] = "<sub>".$char."</sub>";
    }
}

echo $str = str_replace($numbers, $replace, $str);

?>