Search code examples
phpregexpcreregex-lookaroundsregex-group

RegEx for adding a space in a special pattern


Quick note: I know markdown parsers don't care about this issue. It's for the sake of visual consistency in the md file and also experimentation.

Sample:

# this
##that
###or this other

Goal: read each line and,if a markdown header does not have a space after the pound/hashtag sign, add one so that it would look like:

# this
## that
### or this other

My non-regex attempt:

function inelegantFunction (string $string){
    $array = explode('#',$string);
    $num = count($array);
    $text = end($array);
    return str_repeat('#', $num-1)." ".$text;
}

echo inelegantFunction("###or this other"); 
// returns  ### or this other

This works, but it has no mechanism to match the unlikely case of seven '#'.

Regardless of efficacy, I would like to figure out how to do this with regex in php (and perhaps javascript if that matters).


Solution

  • Try to match (?m)^#++\K\S which matches lines starting with one or more number signs then replace it with $0 in your function:

    return preg_replace('~(?m)^#++\K\S~', ' $0', $string);
    

    See live demo here

    To limit the number of #s to six use:

    (?m)^(?!#{7})#++\K\S