downa1234
downa1234

Reputation: 133

how to replace the character?

   $a="dir=desc&order=position&"

i want to replace = to -, & to -.

i using the following code:

           $a = str_replace('&','-',$a);
            $a = str_replace('=','-',$a);

it now turns to dir-desc-order-position-. but i want to get dir-desc-order-position. namely, the last character replace with null "".

Upvotes: 0

Views: 85

Answers (7)

Deepak
Deepak

Reputation: 6802

<?php

$a = "dir=desc&order=position&";    
//Now replace the character '='
$a = str_replace('=', '-', $a);
$result = str_replace('&', '-', $a);
echo rtrim($result,"-");
?>

More on rtrim() refer to @Niet the Dark Absol answer.

Upvotes: 1

Shail
Shail

Reputation: 1575

Remove last character in your string

substr_replace($string ,"",-1);

Upvotes: 0

user1573162
user1573162

Reputation: 47

$a = str_replace('&','-',$a,1);

This will replace & by - for only once.

Upvotes: 0

zed Blackbeard
zed Blackbeard

Reputation: 760

  <?php
  $a = "dir=desc&order=position&";
  $pattern = '/&/';
  $replace = '-';
  $b =preg_replace($pattern , $replace, $a );
  $c = preg_replace('/=/','-',$b);
  echo $c;
  ?>

Upvotes: 0

SumitKhanna
SumitKhanna

Reputation: 44

You can use the trim function if know what character have to remove from string else find the length of your string and use substr function by checking that if how many character needs to be remove from the string end.

Upvotes: 0

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324600

You can use rtrim($a,"-") to remove that character if it exists.

Upvotes: 1

Kevin
Kevin

Reputation: 1706

You can remove the last character with substr($a, 0, -1);

Upvotes: 0

Related Questions