Search code examples
phpregexescapingpreg-replacedelimiter

Regex containing forward slash creates Warning


This function doesn't work:

function remove_ul($ul) {
    $ul = preg_replace('/<ul id="general-nav">/', '<ul class="nav">', $ul, 1);
    $ul = preg_replace('/</ul>/', '<li class="blank"></li></ul>', $ul, 1);
    return $ul;
}

I think it's because of the repeating / on the line with </ul>.


Solution

  • Try replacing this:

    $ul = preg_replace('/</ul>/', '<li class="blank"></li></ul>', $ul, 1);
    

    with:

    $ul = preg_replace('/<\/ul>/', '<li class="blank"></li></ul>', $ul, 1);
    

    Or try:

    $ul = preg_replace('#</ul>#', '<li class="blank"></li></ul>', $ul, 1);
    

    Because in your code, you have specified the delimiter / and then using </ul>, there is conflict, you need to either escape the delimiter with \ or use # as delimiters.