Soptareanu Alex
Soptareanu Alex

Reputation: 5216

Extract substring from string using php

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

Upvotes: 1

Views: 11172

Answers (3)

Kishan Patel
Kishan Patel

Reputation: 485

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.

Upvotes: 0

Blinkydamo
Blinkydamo

Reputation: 1584

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

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

Upvotes: 1

Luis Lavieri
Luis Lavieri

Reputation: 4129

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

Upvotes: 3

Related Questions