1

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

6
  • What is the problem? What do you get? Commented Jan 18, 2023 at 12:56
  • Replace all '-' with '' in your code. And do both trim() without the second parameter. Then you get liznoel-johnevans Commented Jan 18, 2023 at 13:00
  • @WiktorStribiżew I Edited my question with the computed outcome. Commented Jan 18, 2023 at 13:04
  • @Foobar Thank you, I understand the first part, but not exactly sure what to do with "And do both trim()" Commented Jan 18, 2023 at 13:17
  • 1
    Try 3v4l.org/mBMZl Commented Jan 18, 2023 at 13:20

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.