php regex to match algebraic equation within a dynamic string -


i have strings following

3<em>a +</em> 2<em>b</em>  2<em>a </em> - 2<em>b</em> 

and want convert them following

3a + 2b

2a - 2b

strings may or may not have <em></em> tags

basically need parse algebraic equations dynamic string.

following cases code should consider:

2<em>a </em>- (<em>a </em>- 2<em>b)</em> <em>a&nbsp;</em>- 2<em>b</em> <em>a </em>+&nbsp;2<em>b</em> 3<em>a +</em>&nbsp;2<em>b</em> (<em>p</em>&nbsp;+ 2) (<em>p</em>&nbsp;- 3) <em>not algebraic equation. tags should not truncated.</em> 

i tried match above strings using regex, could'nt.

php code:

$string = "3<em>a +</em> 2<em>b</em>"; $pattern = '#(\d{0,9}<em>a.*</em>)#'; preg_match($pattern, $string, $matches); echo json_encode($matches); 

in pattern trying match a inside <em></em> preceded digit.

edit: cannot use strip_tags or related logic truncate out <em></em> because content dynamic , want change match algebraic equation.

you can use strip_tags removing html tags:

$string = "3<em>a +</em> 2<em>b</em>"; echo strip_tags($string);  // second string $string2 = "2<em>a </em> - 2<em>b</em>"; echo strip_tags($string2); 

result:

3a + 2b 2a - 2b 

update:

remove tags if pattern match:

<?php $string = "2<em>a </em> - 2<em>b</em>"; $pattern = '#(\d{0,9}<em>a.*</em>)#'; if(preg_match($pattern, $string, $matches)){     echo strip_tags($matches[0]); } ?> 

Comments

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -