I have a text, and I want to replace all "www.domain.com" with no "?" symbol.
www.domain.com dsa dsad sad sad sa domain.com asdasds adas dsa www.domain.com/someurl/?d sad sadsad www.domain.com/someurl/ asd asd sa www.domain.com?id=123 sd asdsa d
So I am searching the text with the preg_match_all()
, and find all links without "?". Run the loop and when I run str_replace()
it replaces all of the "domain.com" at one time, even the one with the "?" and on the next iteration it add more "add_text" to replaced domain.com, so I get the situation with "domain.com?add_text?add_text" and so on. I have the start position of the text I want to replace from PREG_OFFSET_CAPTURE
, but don't know if it helps me somehow.
Thanks
$post_content = 'www.domain.com dsa dsad sad sad sa
domain.com asdasds adas dsa
www.domain.com/someurl/?d sad sadsad
www.domain.com/someurl/ asd asd sa
www.domain.com?id=123 sd asdsa d'.'<hr>';
$pattern = '#(www\.|https?:\/\/)?(domain.com)\S*#i';
if($num_found = preg_match_all($pattern, $post_content, $out, PREG_OFFSET_CAPTURE))
{
if ($num_found>0){
foreach ($out[0] as $k => $v) {
if (strpos($v, '?') !== false) {
//skip
}else{
//replace
$post_content = str_replace($v, $v.'?add_text, $post_content);
}
}
}
}
Input:
www.domain.com dsa dsad sad sad sa domain.com asdasds adas dsa www.domain.com/someurl/?d sad sadsad www.domain.com/someurl/ asd asd sa www.domain.com?id=123 sd asdsa d
Expected Output:
www.domain.com?add_text dsa dsad sad sad sa domain.com?add_text asdasds adas dsa www.domain.com/someurl/?d sad sadsad www.domain.com/someurl/?add_text asd asd sa www.domain.com?id=123 sd asdsa d
So every URL have a some get param. Every URL with no "?" (get) must be with ?add_text, if there is already a ?something just skip it.