字符串中的下标数字

Nir*_*shi 4 php regex subscript

我想用字符串下标每个数字。

例如 :

$str = '1Department of Chemistry, College of 2Education for Pure Science';
Run Code Online (Sandbox Code Playgroud)

我想要的输出:

<sub>1</sub>Department of Chemistry, College of <sub>2<sub>Education for Pure Science
Run Code Online (Sandbox Code Playgroud)

我从一个字符串中提取了所有数字:

//digits from string 
preg_match_all('!\d+!', $str, $matches);
print_r($matches);
Run Code Online (Sandbox Code Playgroud)

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

Ben*_*enM 5

您可以使用preg_replace

preg_replace( '!\d+!', '<sub>$0</sub>', $str );
Run Code Online (Sandbox Code Playgroud)

演示版