[英]Using PHP preg_replace for this regex
I have two awesome strings:我有两个很棒的字符串:
my_awesome_string
my_awesomestring
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.我正在尝试创建一个 function 如果字符串中有第二个下划线,它可以将第一个下划线转换为
/
,但如果没有第二个下划线,则将其转换为-
。
my/awesome-string
my-awesomestring
my/awesome-string
my-awesomestring
Can you help me convert 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).这个示例代码可以满足您的要求,我发现它相当简单,因为有一个 function 来计算字符串作为字符串一部分的频率(也可以用字符计数 function 替换)。 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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.