Search code examples
phpstr-replace

Variable string replace with multiple occurrences


I am pulling variables from url

$v1 = $_GET[‘v1’]

I am then trying to string replace them but having difficulty getting what I want…

  • I want - (single dash) to stay - (single dash)
  • I want —- (dash dash) to be replace by (single space)
  • I want ——- (dash dash dash) to be replaced by - (space dash space)

I’ve tried the following in the past, but all 3 get replaced by single space every time. Not sure how to revise this to accomplish what I am aiming for this time.

$name = str_replace('--','- ',str_replace('---',' - ',str_replace('-',' ',$v1)));


Solution

  • It is amazing how simple this is. They first requirement solves itself, so all I needed to do was focus on the other 2 bullet points.

    $name = str_replace('--',' ',str_replace('---',' - ',$v2));