我使用正则表达式从给定的字符串中获取多个模式。 在这里,我会清楚地解释你。
$string = "about us";
$newtag = preg_replace("/ /", "_", $string);
print_r($newtag);
以上是我的代码。
在这里,我在一个单词中找到空格并用特殊字符替换空间我需要什么,对吧?
现在,我需要一个正则表达式,它给出了像
这样的模式 如果我将about_us
作为输入,则输出 about-us
,aboutus
,about us
作为输出。
这可能吗?
请帮助我。
提前致谢!
答案 0 :(得分:2)
最后,我的回答是
$string = "contact_us";
$a = array('-','_',' ');
foreach($a as $b){
if(strpos($string,$b)){
$separators = array('-','_','',' ');
$outputs = array();
foreach ($separators as $sep) {
$outputs[] = preg_replace("/".$b."/", $sep, $string);
}
print_r($outputs);
}
}
exit;
答案 1 :(得分:1)
你需要做一个循环来处理多个可能的输出:
$separators = array('-','_','');
$string = "about us";
$outputs = array();
foreach ($separators as $sep) {
$outputs[] = preg_replace("/ /", $sep, $string);
}
print_r($outputs);
答案 2 :(得分:0)
你可以试试没有正则表达式:
$string = 'about us';
$specialChar = '-'; // or any other
$newtag = implode($specialChar, explode(' ', $string));
如果您将特殊字符放入数组中:
$specialChars = array('_', '-', '');
$newtags = array();
foreach ($specialChars as $specialChar) {
$newtags[] = implode($specialChar, explode(' ', $string));
}
您也可以只使用str_replace()
foreach ($specialChars as $specialChar) {
$newtags[] = str_replace(' ', $specialChar, $string);
}
答案 3 :(得分:0)
我不确切地知道你想做什么我希望你可能想用一个破折号替换任何非单词(1次或更多次)。
e.g。
preg_replace('/\W+/', '-', $string);
答案 4 :(得分:0)
如果您只想更换空间,请使用\ s
<?php
$string = "about us";
$replacewith = "_";
$newtag = preg_replace("/\s/", $replacewith, $string);
print_r($newtag);
?>
答案 5 :(得分:0)
我不确定正则表达式是否适用于此。但是,您可以简单地定义这种功能:
function rep($str) {
return array( strtr($str, ' ', '_'),
strtr($str, ' ', '-'),
str_replace(' ', '', $str) );
}
$result = rep('about us');
print_r($result);
答案 6 :(得分:0)
匹配任何不是单词字符的字符
$string = "about us";
$newtag = preg_replace("/(\W)/g", "_", $string);
print_r($newtag);
以防它只是...如果它是一个更长的字符串你会遇到问题:)