使用 PHP 函数生成搜索引擎友好的 URL

生成搜索引擎友好 (SEF) URL 可以显着改善您的搜索引擎结果。 “/post.php?id=2382”和“/great-php-functions/”之间有很大的区别。拥有搜索引擎友好的 URL 还可以让用户了解如果链接文本不充分,他们将在页面上单击什么。

我已经创建了姊妹 PHP 函数来为我为客户创建的 CMS 生成搜索引擎友好的 URL。这个想法很简单。我获取用户创建的页面标题并将其提供给清理功能以:

  • 删除所有标点符号
  • 将 URL 切换为小写
  • 删除空格,替换为给定的分隔符(在本例中为破折号)
  • 删除重复的词
  • 删除对 SEO 没有帮助的词

代码

/* takes the input, scrubs bad characters */
function generate_seo_link($input, $replace = '-', $remove_words = true, $words_array = array()) {
	//make it lowercase, remove punctuation, remove multiple/leading/ending spaces
	$return = trim(ereg_replace(' +', ' ', preg_replace('/[^a-zA-Z0-9\s]/', '', strtolower($input))));

	//remove words, if not helpful to seo
	//i like my defaults list in remove_words(), so I wont pass that array
	if($remove_words) { $return = remove_words($return, $replace, $words_array); }

	//convert the spaces to whatever the user wants
	//usually a dash or underscore..
	//...then return the value.
	return str_replace(' ', $replace, $return);
}

/* takes an input, scrubs unnecessary words */
function remove_words($input,$replace,$words_array = array(),$unique_words = true)
{
	//separate all words based on spaces
	$input_array = explode(' ',$input);

	//create the return array
	$return = array();

	//loops through words, remove bad words, keep good ones
	foreach($input_array as $word)
	{
		//if it's a word we should add...
		if(!in_array($word,$words_array) && ($unique_words ? !in_array($word,$return) : true))
		{
			$return[] = $word;
		}
	}

	//return good words separated by dashes
	return implode($replace,$return);
}

解释

该函数接受四个值:

  1. $input – string – 将进行 SEO,在我的例子中,页面标题
  2. $replace – string -单词分隔符,在大多数情况下是破折号或下划线
  3. $remove_words – 布尔值 – 删除特定的、无用的 SEO 单词
  4. $words_array – array – 应该从每个 URL 中删除的单词数组,因为它们对 SEO 没有帮助

示例结果

$bad_words = array('a','and','the','an','it','is','with','can','of','why','not');
echo generate_seo_link('Another day and a half of PHP meetings', '-', true, $bad_words);
//displays :: another-day-half-php-meetings

echo generate_seo_link('CSS again?  Why not just PHP?', '-', true, $bad_words);
//displays :: css-again-just-php

echo generate_seo_link('A penny saved is a penny earned.', '-', true, $bad_words);
//displays :: penny-saved-earned

帮自己一个忙 – 使用干净的 URL 让您的动态页面对搜索引擎更友好!

赞(0) 打赏

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏