1

I need to extract a substring from another string using php.

$string = 'This is my string that conteined a Code:XYZ123';
$code = substr($text, -1, strpos($string,'Code:'));
echo $code ; // return 3

I need the whole code for example XYZ123

0

3 Answers 3

3

You need the starting position of "Code:" plus the length of "Code:"

$string = 'This is my string that conteined a Code:XYZ123'; 
$code = substr($string, strpos($string,'Code:') + 5); 
echo $code; //XYZ123
Sign up to request clarification or add additional context in comments.

Comments

1

Another option is to explode the string my Code: and echo the second part of the array

$code = explode( 'Code:', $string );
echo $code[ 1 ]

Comments

0

Try this code :

$string = 'This is my string that conteined a Code:XYZ123';
$code = substr($string ,strpos($string,'Code:'));
echo $code;

Make sure this is helpful to you.

2 Comments

The output to this is Code:XYZ123
Yeah he wants the actual code. Not 'Code:' plus the code

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.