convert title to slug in php | sanitize_title() in php
Example to convert title to slug in php
$title = "This is a Sample Title!";
$slug = sanitize_title($title);
echo $slug; // Outputs: "this-is-a-sample-title"
Function defination /explaination
<?php
function sanitize_title($title) {
$title = strip_tags($title); // remove HTML and PHP tags
$title = preg_replace('/[\r\n\t ]+/', ' ', $title); // replace new lines, tabs, and multiple spaces with a single space
$title = trim($title); // remove leading and trailing spaces
$title = strtolower($title); // convert to lowercase
$title = preg_replace('/[^a-z0-9\-]/', '', $title); // remove anything that is not a lowercase letter, number, or hyphen
$title = preg_replace('/-+/', '-', $title); // replace multiple hyphens with a single one
return $title;
}
?>