Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subscript digits from a string

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 ?

like image 219
Nirali Joshi Avatar asked Mar 15 '23 13:03

Nirali Joshi


2 Answers

You can use preg_replace:

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

Demo

like image 78
BenM Avatar answered Mar 23 '23 13:03

BenM


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);
like image 40
Manwal Avatar answered Mar 23 '23 11:03

Manwal