urlify icon indicating copy to clipboard operation
urlify copied to clipboard

Difficulty generating a slug with / and ,

Open LeandroCD opened this issue 2 years ago • 1 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.

LeandroCD avatar Jan 05 '24 13:01 LeandroCD

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!

lux avatar Jan 11 '24 15:01 lux