Reputation: 1
I want to match an array against a string and replace city name contained in string with a dash (-)
For example:
$str = 'French Tuition In Newyork' OR $str = 'French Tuition Newyork';
$arrCity = array('Newyork', 'Washington');
I want to replace the above strings like below,
$str = 'French Tuition - Newyork' AND $str = 'French Tuition - Newyork';
Thus if last word is city it should be pre-appended by dash (-). OR If the last word is city and before last word is "IN", the "IN" should be replaced by dash (-).
Upvotes: 0
Views: 144
Reputation: 959
This's effective one ;)
<?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);
?>
Output
French Tuition - Washington
French Tuition - Newyork
Upvotes: 0
Reputation: 11
<?php
$str = 'French Tuition Washington';
$arrCity = array('Newyork', 'Washington');
$cities = implode('|', $arrCity);
echo preg_replace("/(French Tuition).+({$cities})/", '$1 - $2', $str);
?>
Upvotes: 1
Reputation: 656
You can simply do it with this.
<?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);
?>
Upvotes: 0
Reputation: 2806
For your reference.
<?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;
}
}
?>
Upvotes: 2