Happy
Happy

Reputation: 891

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>.

Upvotes: 0

Views: 715

Answers (2)

Escape the slash in the second expression (/<\/ul>/). If your query becomes more complex, you might have to use a capturing group as well (parentheses).

Oh and parsing html with regex is evil. In before the XHTML Regex bandwagon storms this post. :)

Upvotes: 1

Sarfraz
Sarfraz

Reputation: 382909

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.

Upvotes: 4

Related Questions