Skip to content

simpletoc_sanitize_string - ensure valid ID string #66

Open
@bwmatter

Description

@bwmatter

If a user creates a heading tag that begins with anything but 'a-z', the scrollTo links do not work.

ex.

1 Step for Man, 1 Step for Mankind

The id would be:
<h2 id="1-step-for-man-1-step-for-mankind">1 Step for Man, 1 Step for Mankind</h2>

I tested this by modifying the plugin's code (I couldn't override it in my theme).

function simpletoc_sanitize_string($string)
{
    // remove punctuation
    $zero_punctuation = preg_replace("/\p{P}/u", "", $string);
    // remove non-breaking spaces
    $html_wo_nbs = str_replace("&nbsp;", " ", $zero_punctuation);
    // remove umlauts and accents
    $string_without_accents = remove_accents($html_wo_nbs);
    // Sanitizes a title, replacing whitespace and a few other characters with dashes.
    $sanitized_string = sanitize_title_with_dashes($string_without_accents);
    if (preg_match("/^[_a-zA-Z]+$/", $sanitized_string)){
      // Encode for use in an url
      $urlencoded = urlencode($sanitized_string);
    } else {
      // Encode for use in an url
      $id_prefix = 'simpletoc-header-';
      $sanitized_string = $id_prefix . $sanitized_string;
      $urlencoded = urlencode($sanitized_string);
    }
    
    return $urlencoded;
}

$id_prefix can be whatever you want, I just used "simpletoc-header" since I think it's unlikely anyone would ever use "Simpletoc Header"

Can you make this function either override-able or consider modifying the code altogether? I think it'd be a great enhancement.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions