开发者

Using PHP preg_replace for this regex

开发者 https://www.devze.com 2023-03-18 06:27 出处:网络
I have two awesome strings: my_awesome_string my_awesomestring I\'m trying to create a function that can convert the first underscore to a / if there is a second underscore in the string, but conver

I have two awesome strings:

my_awesome_string my_awesomestring

I'm trying to create a function that can convert the first underscore to a / if there is a second underscore in the string, but convert it to a - if there is no second underscore.

my/awesome-string my-awesomestring

Can you help me conv开发者_C百科ert my awesome string?


Another way:

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


This example code does what you asked for, I found it rather trivial as there is a function to count how often a string is part of a string (could be replaced with the char counting function as well). 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));


If I understand your question correctly, something like this should work:

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

精彩评论

暂无评论...
验证码 换一张
取 消