2

How to get a part of string using PHP?

I have a string like this.

$str = 'href="http://www.idontknow.com/areyousure?answer=yes"';

I want only the link.. like this

$str_new = "http://www.idontknow.com/areyousure?answer=yes";
1
  • 2
    What kind of strings you expect to get in $str? Maybe substr() won't help and you'll need to use REGEXP. Commented Jul 25, 2011 at 10:51

5 Answers 5

5
$str_new = substr($str, 6, -1);

substr()

If length is given and is positive, the string returned will contain at most length characters beginning from start (depending on the length of string).

If length is given and is negative, then that many characters will be omitted from the end of string (after the start position has been calculated when a start is negative). If start denotes the position of this truncation or beyond, false will be returned.

If length is given and is 0, FALSE or NULL an empty string will be returned.

If length is omitted, the substring starting from start until the end of the string will be returned.

Sign up to request clarification or add additional context in comments.

Comments

4
$str = 'href="http://www.idontknow.com/areyousure?answer=yes"';
preg_match('/href="(.*)"/', $str, $matches);
$str_new = $matches[1];

echo $str_new;

Output:

http://www.idontknow.com/areyousure?answer=yes

Comments

0

Try

$result = substr($input, 6, strlen($input) - 1);

Comments

0

Use a regular expression:

$str = 'href="http://www.idontknow.com/areyousure?answer=yes"';
$string = preg_replace ( '/href="(.*)"/', '\1', $str );

Comments

0
$str = preg_replace('/href=/i', '', $str);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.