I want to subscript every digits from string.
For example :
$str = '1Department of Chemistry, College of 2Education for Pure Science';
Output I want:
<sub>1</sub>Department of Chemistry, College of <sub>2<sub>Education for Pure Science
I fetched all digits from a string :
//digits from string
preg_match_all('!\d+!', $str, $matches);
print_r($matches);
But how can i apply subscript effect to digits and print string ?
You can use preg_replace
:
preg_replace( '!\d+!', '<sub>$0</sub>', $str );
Demo
This may help:
$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);
Will give output:
<sub>1</sub>Department of Chemistry, College of <sub>2</sub>Education for Pure Science
Or preg_replace
will give same output:
$str = '1Department of Chemistry, College of 2Education for Pure Science';
$str = preg_replace( '!\d+!', '<sub>$0</sub>', $str );
echo htmlentities($str);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With