Reputation: 215
I have a set of string like this:
$string1 = 'man_city/man_united'; //it will be replaced
$string2 = 'liverpool///arsenal'; //it will not be replaced
$string3 = 'chelsea//spurs'; //it will not be replaced
$string4 = 'leicester/sunderland'; //it will be replaced
i want to replace the '/' character from string with '/' but only if next or previous character from '/' character not containing '/' too.
if i use str_replace like this, it won't work:
$name1 = str_replace("/","\/",$string1);
$name2 = str_replace("/","\/",$string2);
...
//output
$name1 = 'man_city\/man_united';
$name2 = 'liverpool\/\/\/arsenal';
...
//desired output
$name1 = 'man_city\/man_united';
$name2 = 'liverpool///arsenal';
...
Upvotes: 3
Views: 1764
Reputation: 626961
You may use
'~(?<!/)/(?!/)~'
See the regex demo.
The (?<!/)
negative lookbehind will fail the match if there is a /
before /
and (?!/)
negative lookahead will fail the match if there is a /
after /
.
$re = '~(?<!/)/(?!/)~';
$str = "man_city/man_united\nliverpool///arsenal\nchelsea//spurs\nleicester/sunderland";
$result = preg_replace($re, "\\/", $str);
echo $result;
Output:
man_city\/man_united
liverpool///arsenal
chelsea//spurs
leicester\/sunderland
Upvotes: 4
Reputation: 23327
You can try with negative lookarounds:
$name = preg_replace("/(?<!\/)\/(?!\/)/","\/",$string1);
Explanation:
(?<!\/)\/(?!\/)
(?<!\/)
negative lookbehind - matches a place in the string that is nontpreceded with /
\/
matches '/'(?!\/)
negative lookahead - matches place in the string not followed by /
`Upvotes: 0
Reputation: 2277
I thinks this can help you:
<?php
$string1 = 'man_city/man_united'; //it will be replaced
if(!substr_count($string1, '//')){
$string1 = str_replace('/','#',$string1); //Do replace accordingly
}
echo $string1;
Upvotes: 0
Reputation: 927
In this case it's easier to use a regular expression (=> preg_replace()
).
e.g. preg_replace(#/+#, '/', $str)
Upvotes: 0