Search code examples
phpwoocommercepreg-replacestr-replace

Preg_replace string


I am creating a username from the users Billing First Name and Billing Last Name. This in in. WooCommerce, though I suppose the cms is irrelevant to my question.

The following characters should be removed: ! @ # $ % ^ & * ( ) ~ ` , . : ' " ; ; > < ? / \ |

Any number should be removed The string must be in lowercase All spaces must be replaced with hyphen.

Below is what I tried:

if(isset($_POST['billing_first_name']))
    $fn = $_POST['billing_first_name'];
$fn = iconv('utf-8', 'us-ascii//TRANSLIT', $fn);
$fn = preg_replace('/[^a-z0-9-]+/', '-', strtolower($fn));
$fn = preg_replace("/-+/", '-', $fn);
$fn = trim($fn, '-');

if(isset($_POST['billing_last_name']))
    $ln = $_POST['billing_last_name'];
$ln = iconv('utf-8', 'us-ascii//TRANSLIT', $ln);
$ln = preg_replace('/[^a-z0-9-]+/', '-', strtolower($ln));
$ln = preg_replace("/-+/", '-', $ln);
$ln = trim($ln, '-');

Example:

fn = Liz & Noël;
ln = John-Evan’s 2nd;
echo $fn . '-' . $ln;

Expected Outcome: liznoel-johnevansnd

Computed Outcome: liz-no-eljohn-evan-s-2nd


Solution

  • You can use

    <?php
    
    $fn = 'Liz & Noël';
    $ln = 'John-Evan’s 2nd';
    
    function process( $str )
    {
        $str = iconv('utf-8', 'us-ascii//TRANSLIT', $str);
        $str = strtolower($str);
        return preg_replace('~[^A-Za-z]+~u', '', $str);
    }
    
    echo process($fn) . '-' . process($ln);
    

    Note that preg_replace('~[^A-Za-z]+~u', '', $str); removes any char other than an ASCII letter from any Unicode string. Since the hyphen appears between the two name parts, you cannot replace with a hyphen, you need to create the string from two parts using concatenation.