English 中文(简体)
缩短此函数
原标题:Shortening this function
  • 时间:2012-05-23 15:48:19
  •  标签:
  • php
  • regex
  • url

我写了这个代码来准备链接的标题, 但我觉得它有点粗略, 想知道如果有人能更清楚地了解 regex, 可以减少以下功能( 通过合并相关的预置替换 ) 。 我需要它去掉所有的当前连字符, 脱去多个空格, 确保它除了空间替换连字符之外, 仅是字母数字, 用单一连字符替换所有空格, 并确保字符串不会以连字符开头 :

function prepareURLTitle($title)
{

return preg_replace("/A-/", "", str_replace(" ", "-", preg_replace("/[^a-zA-Z0-9s]/", "", preg_replace( /ss+/ ,    , preg_replace( /s?-/ ,   , $title)))));

}

输入和输出的例子 :

输入 :

BRANND New - 手套, 2包/// 多个空间都在这里, 但区段方位不允许我展示它们

产出:

BRAND-NEW-Gloves-2号包

问题回答
trim(preg_replace( `[^a-z0-9]+`i , - ,str_replace(" ",  ,$title)), - )

我还用空话取代了引号, 所以像"猫叫"那样的弦不会变成"猫叫"

function prepareURLTitle($title)
{
   return preg_replace("[^A-Za-z0-9]+", "-", $title);
}

这将有效。 您需要用一个“ -” 来替换“ 强” 多功能 < /强” 非数字字符 。

preg_replace( ~[^a-zd]+~i , - ,preg_replace( ~^[^a-zd]+(.*?)[^a-zd]+$~i , $1 ,$title));
// or
preg_replace(array( ~^[^a-zd]+(.*?)[^a-zd]+$~i , ~[^a-zd]+~i ),array( $1 , - ),$title);

举个例子...

$title =    BRAND   NEW -   Gloves, 2 pack -   ;
echo preg_replace(array( ~^[^a-zd]+(.*?)[^a-zd]+$~i , ~[^a-zd]+~i ),array( $1 , - ),$title);

将返回

BRAND-NEW-Gloves-2号包

function prepareURLTitle($title)
{
   return preg_replace( "/[^a-zA-Z0-9]/", "-",str_replace("-", "",  $title));
}

DEMO:“http://codepad.org/lPSBys' rel=“nofollow'>http://codepad.org/lPSBys

输出 :

BRAND - NEW - GLOVES - 2号包





相关问题
Brute-force/DoS prevention in PHP [closed]

I am trying to write a script to prevent brute-force login attempts in a website I m building. The logic goes something like this: User sends login information. Check if username and password is ...

please can anyone check this while loop and if condition

<?php $con=mysql_connect("localhost","mts","mts"); if(!con) { die( unable to connect . mysql_error()); } mysql_select_db("mts",$con); /* date_default_timezone_set ("Asia/Calcutta"); $date = ...

定值美元

如何确认来自正确来源的数字。

Generating a drop down list of timezones with PHP

Most sites need some way to show the dates on the site in the users preferred timezone. Below are two lists that I found and then one method using the built in PHP DateTime class in PHP 5. I need ...

Text as watermarking in PHP

I want to create text as a watermark for an image. the water mark should have the following properties front: Impact color: white opacity: 31% Font style: regular, bold Bevel and Emboss size: 30 ...

How does php cast boolean variables?

How does php cast boolean variables? I was trying to save a boolean value to an array: $result["Users"]["is_login"] = true; but when I use debug the is_login value is blank. and when I do ...

热门标签