• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 591
  • Last Modified:

Replace first character in string

This seems rather trivial, but what I want to do is if a string starts with a forward slash, remove it.

So:

$str = "/something/else";

If this occurs, get rid of the first slash to make it:

$str = "something/else";

I have a preg and not sure if this is correct?

preg_replace("/^\\{1}/", $str, $output);

Does this look right?  Or is there a faster str_replace type funtion to use.
0
LinuxNubb
Asked:
LinuxNubb
  • 4
  • 4
  • 2
2 Solutions
 
RoonaanCommented:
You can juse use /^\\/ , but indeed substr and str_replace should be faster I think.

-r-
0
 
LinuxNubbAuthor Commented:
what would be the str_replace or substr version?  str_replace replaces all slashes, not just the starting.
0
 
Harisha M GCommented:
$str = "/something";
$str = preg_replace("#^/#","", $str);
echo $str;
0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
RoonaanCommented:
Sorry, no str_replace involved

if(substr($str,0,1) == '\\') $str = substr($str,1);

-r-
0
 
Harisha M GCommented:
Or, if you want the output to be in $output..

$str = "/something";
$output = preg_replace("#^/#","", $str);
echo $output;


Note that you don't have to replace anything if the first character is not /. So, str_replace won't help
0
 
LinuxNubbAuthor Commented:
what does the # do in the preg_replace mgh?
0
 
Harisha M GCommented:
It would be faster than any other:

$output = $str[0]=="/" ? substr($str,1) : $str;
0
 
Harisha M GCommented:
LinuxNubb, it is arbitrary. You can choose any special character. But if you use / (as most of the times we do), then you need to escape the real / that we need to replace.

But I would suggest my previous suggestion..
$output = $str[0]=="/" ? substr($str,1) : $str;
0
 
LinuxNubbAuthor Commented:
lol, sometimes I don't know about myself!

I wasn't replace my preg with ''

preg_replace("/^\\{1}/", $str, $output);

should be:

preg_replace("/^\\{1}/", '', $str);
0
 
LinuxNubbAuthor Commented:
Points to both for many working examples.
0

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 4
  • 4
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now