使用PHP preg_replace为此正则表达式

时间:2011-07-06 17:42:02

标签: php regex

我有两个很棒的字符串:

my_awesome_string my_awesomestring

如果字符串中有第二个下划线,我正在尝试创建一个可以将第一个下划线转换为/的函数,但如果没有第二个下划线,则将其转换为-

my/awesome-string my-awesomestring

你能帮我转换我真棒的字符串吗?

3 个答案:

答案 0 :(得分:3)

另一种方式:

$first = strpos($str, '_');          // find first _
$last = strrpos($str, '_');          // find last _
$str = str_replace('_', '-', $str);  // replace all _ with -
if($first !== $last) {               // more than one _ ?
    $str[$first] = '/';              // replace first with /
}

答案 1 :(得分:1)

这个示例代码完成了你所要求的,我发现它相当微不足道,因为有一个函数来计算字符串是字符串的一部分的频率(也可以用char计数函数替换)。 Demo

<?php

$strings = array(
    'my_awesome_string',
    'my_awesomestring'
);

function convert_underscore($str) {
    $c = substr_count($str, '_');
    if (!$c) return $str;
    $pos = strpos($str, '_');
    $str = str_replace('_', '-', $str);
    ($c>1) && $str[$pos] = '/';
    return $str;
}

print_r(array_map('convert_underscore', $strings));

答案 2 :(得分:0)

如果我理解你的问题,这样的事情应该有效:

if( substr_count($str, '_') > 1 ) $str = preg_replace('/_/', '/', $str, 1);
$str = str_replace('_', '-', $str);