Regex delete letter H and any numbers after it

Help with the correct regular expression in PHP. I have a line (the chemical formula of a linear format) in which I want to replace the letter " H " (or) the letter " H ", followed by numbers.

For example:

CH3NO+       -> CNO+
C12H17ClN4OS -> C12ClN4OS
CNO3         -> CNO3
H2O          -> O
CHO          -> CO
+4
source share
2 answers

This will be done:

$newVariable = preg_replace('~H\d*~', '', $yourVariable);

\d* means it will match if there are 0 or more matching digits.

+3
source

Use this to solve your goal.

<?php
$test = "CH3NO+";
echo preg_replace("/H\d+/i","",$test);
?>
+1
source

Source: https://habr.com/ru/post/1623196/


All Articles