我希望将数组与字符串匹配,并将字符串中包含的城市名称替换为短划线( - )
例如:
$str = 'French Tuition In Newyork' OR $str = 'French Tuition Newyork';
$arrCity = array('Newyork', 'Washington');
我想替换上面的字符串,如下所示,
$str = 'French Tuition - Newyork' AND $str = 'French Tuition - Newyork';
因此,如果最后一个单词是城市,则应该用破折号( - )预先附加。 要么 如果最后一个单词是city,并且在最后一个单词是“IN”之前,则“IN”应该用短划线( - )替换。
答案 0 :(得分:2)
供您参考。
<?php
//$str = 'French Tuition Newyork';
$str = 'French Tuition In Washington';
$arrCity = array('Newyork', 'Washington');
$in_str = 'In';
foreach ($arrCity as $key => $value) {
$pos = strpos($str, $value);
if($pos) {
$pos2 = strpos($str, $in_str);
if($pos2)
$temp_str = explode($in_str, $str);
else
$temp_str = explode($value, $str);
$result = $temp_str[0] . ' - ' . $value;
echo $result;
}
}
?>
答案 1 :(得分:1)
<?php
$str = 'French Tuition Washington';
$arrCity = array('Newyork', 'Washington');
$cities = implode('|', $arrCity);
echo preg_replace("/(French Tuition).+({$cities})/", '$1 - $2', $str);
?>
答案 2 :(得分:0)
你可以这样做。
<?php
$str = 'French Tuition In Newyork';
$str2 = 'French Tuition Newyork';
$arrCity = array('Newyork', 'Washington');
$temp = array();
$split = explode(" ", $str);
$lastword = $split[count($split)-1];
$beforeLastWord = $split[count($split)-2];
if(in_array($lastword, $arrCity)) {
if(strtolower($beforeLastWord) === 'in') {
$split[count($split)-2] = '-';
}
else {
$split[count($split)-1] = '-';
array_push($split, $lastword);
}
}
echo implode(" ", $split);
?>
答案 3 :(得分:0)
这是有效的;)
<?php
$str = 'French Tuition In Washington';
$str1 = 'French Tuition Newyork';
function dash($string)
{
if (strpos($string,'In') !== false)
{
echo str_replace('In','-',$string);
}
else
{
$arrCity = array('Newyork', 'Washington');
foreach($arrCity as $city)
{
if(strpos($string,$city))
{
echo str_replace($arrCity,'- '.$city,$string);
}
}
}
}
dash($str);
dash($str1);
?>
输出
French Tuition - Washington
French Tuition - Newyork