dongping1922 2014-09-18 16:19
浏览 7
已采纳

RegEx只使用一个*而不是两个

I was working on this regex that I use in preg_replace to add divs and /divs around text that has * around it. It right now use two *s. What would be a sure way to do it with only one *

Current

<?php

$errors = 1;

$arr['ERR'] = '';
$arr['ERR'] .= '*<i>Error 1</i>*';
$arr['ERR'] .= '*<i>Error 2</i>*';
$arr['ERR'] .= '*<i>Error 3</i>*';
$arr['ERR'] .= '*<i>Error 4</i>*';
$arr['ERR'] .= '*<i>Error 5</i>*';
$arr['TOF'] = 'Success';

$arr = preg_replace('#\*(.+?)\*#', '<div>$1</div>', $arr);

print_r( $arr );
// output


array (
    [ERR] => <div><i>Error 1</i></div><div><i>Error 2</i></div><div><i>Error 3</i></div><div><i>Error 4</i></div><div><i>Error 5</i></div>
    [TOF] => Success
)



?>

Attempting

$arr['ERR'] = '';
$arr['ERR'] .= '*<i>Error 1</i>';
$arr['ERR'] .= '*<i>Error 2</i>';
$arr['ERR'] .= '*<i>Error 3</i>';
$arr['ERR'] .= '*<i>Error 4</i>';
$arr['ERR'] .= '*<i>Error 5</i>';
$arr['TOF'] = 'Success';

$arr = preg_replace('#\*(.+?)#', '<div>$1</div>', $arr);

//just one * but get the same results as above.

How can the regex be done to use only one *

  • 写回答

1条回答 默认 最新

  • dongque1462 2014-09-18 16:22
    关注

    You can use this regex:

    \*(.+?)(?![^*])
    

    The lookahead asserts that the match is before another star or at the end of the match.

    Here is a regex demo.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?