Convert string to slug and other custom string functions

Recently I needed a function to convert a company name into a slug. As an example this slug is for the URL of a customer detail page. Since those names (the customer database table has more than 1300 records) contains special characters like “é” or “ë”, I needed a function that can handle this too. A quick Google search has provided something like this:

function convert_to_slug($str) {
	$str = strtolower(trim($str));
	$str = preg_replace('/[^a-z0-9-]/', '-', $str);
	$str = preg_replace('/-+/', "-", $str);
	rtrim($str, '-')
}

This function is quick and dirty and will create a nice slug, special characters are replace with dashes and multiple dashes are replace by single dashes. The slug is okay because it’s not very often that a special char need to get replaced. Another problem I need to solve is that the slugs need to be unique as well. So I need function that is able to check existing slugs and will add number to the end if necessary.

function check_slug($slug, $conn) {
	$invalidSlug = true;
	$count = 1;
	while ($invalidSlug) {
		$sql = sprintf("SELECT ID FROM org_meta WHERE slug = '%s'", $conn->real_escape_string($slug));
		$res = $conn->query($sql);
		if ($res->num_rows > 0) {
			$count++;
			if ($count == 2) {
				$slug = $slug.'-'.$count;
			} else {
				$slug++;
			}
			continue;
		} else {
			$invalidSlug = false;
		}
	}
	return $slug;
}

You can use that function like (you need to pass a database connection string too):

$new_slug = check_slug($slug, $db);

PHP string / word wrapper

I wrote this function because the native PHP function wordwrap() doesn’t fit the needs of a regular web page. Just enter for this function the string, the row limit and if you like the divider. This function breaks the line after the character limit is reached.

function text_wrap($log_text, $limit, $divider=" ") {
    $words = explode($divider, $log_text);
    $word_count = count($words);
    $char_counter = 0;
    $block = "";
    foreach ($words as $value) {
        $chars = strlen($value);
        $block .= $value;
        $char_counter = $char_counter + $chars;
        if ($char_counter >= $limit) {
            $block .= " \\n ";
            $char_counter = 0;
        } else {
            $block .= " ";
        }
    }
    return rtrim($block);
}

This example will create 4 rows of text (maybe more)

echo text_wrap($some_text_with_100chars, 25, " ");

Rebuild query string

The function is very useful for pagination functions or for passing variables from one page to another page. In this version it’s possible to add more than one variable names into the functions arguments. These names will be filtered from the new generated query string. Just add the variable names you don’t need into a comma separated string.

function rebuild_qs($curr_vars) {
    if (!empty($_SERVER['QUERY_STRING'])) {
        $parts = explode("&", $_SERVER['QUERY_STRING']);
        $curr_vars = str_replace(" ", "", $curr_vars); // remove whitespace
        $c_vars = explode(",", $curr_vars);
        $newParts = array();
        foreach ($parts as $val) {
            $val_parts = explode("=", $val);
            if (!in_array($val_parts[0], $c_vars)) {
                array_push($newParts, $val);
            }
        }
        if (count($newParts) != 0) {
            $qs = "&".implode("&", $newParts);
        } else {
            return false;
        }
        return $qs; // this is your new created query string
    } else {
        return false;
    }
}

Example:

<a href="script.php?ident=1<?php echo rebuild_qs("ident, submit, var_one"); ?>">link</a>