繁体   English   中英

对这个正则表达式使用 PHP preg_replace

[英]Using PHP preg_replace for this regex

我有两个很棒的字符串:

my_awesome_string my_awesomestring

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

my/awesome-string my-awesomestring

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

另一种方式:

$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 /
}

这个示例代码可以满足您的要求,我发现它相当简单,因为有一个 function 来计算字符串作为字符串一部分的频率(也可以用字符计数 function 替换)。 演示

<?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));

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM