jbroadway / urlify

A fast PHP slug generator and transliteration library that converts non-ascii characters for use in URLs.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Difficulty generating a slug with / and ,

LeandroCD opened this issue · comments

When generating a slug that contains / and , , it replaces these characters with nothing, when it should correctly replace them with a separator.

  • Test string: Bomba Submersa 1/4HP 0,25 110V Lepono
  • Incorrect: bomba-submersa-14hp-025-110v-lepono
  • Correct: bomba-submersa-1-4hp-0-25-110v-lepono

I modified the following code snippet:

$string = (string) \preg_replace(
            [
                // 1) remove un-needed chars
                '/[^' . $separatorEscaped . $removePatternAddOn . '\-a-zA-Z0-9\s]/u',
                // 2) convert spaces to $separator
                '/[\s]+/u',
                // 3) remove some extras words
                $removeWordsSearch,
                // 4) remove double $separator's
                '/[' . ($separatorEscaped ?: ' ') . ']+/u',
                // 5) remove $separator at the end
                '/[' . ($separatorEscaped ?: ' ') . ']+$/u',
            ],
            [
                '',
                $separator,
                '',
                $separator,
                '',
            ],
            $string
        );

To:

$string = (string) \preg_replace(
            [
                // 1) remove un-needed chars
                '/[^' . $separatorEscaped . $removePatternAddOn . '\-a-zA-Z0-9\s]/u',
                // 2) convert spaces to $separator
                '/[\s]+/u',
                // 3) remove some extras words
                $removeWordsSearch,
                // 4) remove double $separator's
                '/[' . ($separatorEscaped ?: ' ') . ']+/u',
                // 5) remove $separator at the end
                '/[' . ($separatorEscaped ?: ' ') . ']+$/u',
            ],
            [
                $separator,
                $separator,
                '',
                $separator,
                '',
            ],
            $string
        );

And it worked correctly.

Ah yes, it simply strips those out by default. An easier way to add them would be to do this:

<?php

require_once 'vendor/autoload.php';

URLify::add_chars ([
	'/' => '-',
	',' => '-'
]);

echo URLify::slug ('Bomba Submersa 1/4HP 0,25 110V Lepono') . PHP_EOL;

Hope that helps!