Sunday, 15 June 2014

php - Detecting if characters surrounding a given string are evenly matched -



php - Detecting if characters surrounding a given string are evenly matched -

i building piece of script has pseudo-markdown in it.

wrapping string in asterisks (*) create text bold, replacing characters <strong>string</strong> wrapping string in carats (^) create text emphasized, replacing characters <em>string</em>

i using next regular look path evaluate this:

$src = preg_replace('/\*([^*]*)\*/', "<strong>$1</strong>", $inputtext); $in = preg_replace('/\^([^^]*)\^/', "<em>$1</em>", $src); $output = rtrim(preg_replace("/(^[\n\n]*|^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/", "\n", $in), "\r\n");

this next tasks:

replaces asterisks <strong> tags replaces carats <em> tags strips blank lines, , takes out trailing newline character

my problem

in validation, want prevent occurrence of misplaced markdown. if user enters: *^this test^*, work fine. if come in (inadvertently) *^this test*^, result in html <strong><em>this test</strong></em> of course, invalid markup.

i want prevent in validation methods, not sure how parse in such way checks appropriately matched pairs. how can accomplish this?

you can proceed this:

$data = ' markdown. if user enters: *^this test^*, work fine. if come in (inadvertently) *^this test*^, will'; $pattern = '~([*^])((?>[^^*]+|(?r))+)\1~'; $corr = array('*' => 'strong', '^' => 'em'); { $data = preg_replace_callback($pattern, function($m) utilize ($corr) { homecoming '<' . $corr[$m[1]] . '>' . $m[2] . '</' . $corr[$m[1]] . '>'; }, $data, -1, $count); } while ($count > 0); echo htmlspecialchars($data);

note: can alter lastly quantifier + * if want allow empty strings (i.e. <em></em> or <strong></strong>).

an other way uses stack:

$stack = array(); $arr = preg_split('~([*^])~', $data, -1, preg_split_delim_capture); ($k = 1; $k<count($arr); $k+=2) { $lval = end($stack); $lkey = key($stack); if ($lval == $arr[$k]) { $arr[$lkey] = '<' . $corr[$lval] . '>'; $arr[$k] = '</' . $corr[$lval] . '>'; array_pop($stack); } else { $stack[$k]=$arr[$k]; } } $result = implode('',$arr);

php regex string markdown

No comments:

Post a Comment