jose sanchez
jose sanchez

Reputation: 51

PHP Code replace whit Regular expressions

I have my site on series, usually all series are divided by seasons and episodes, I have the following string: The Mentalist S05E14

where **S05E14** is like **Episode 14 Season 05** I need to change the expression:

**S05E14** 
   for 
**05x14**

Also, for any season and episode, so I would remove "S" and replace the "E" for "x"

How can I do this using regular expressions or perhaps otherwise?

Upvotes: 2

Views: 134

Answers (4)

shivam
shivam

Reputation: 1140

Try this:

$string_val="The Mentalist S05E14";
$data = explode(' ', $text);
$count = count($data);
$last_word = $data[$count-1];
$newStr = str_replace("S", "", $last_word);
$newStr = str_replace("E", "x", $newStr);

Upvotes: 0

hjpotter92
hjpotter92

Reputation: 80639

echo preg_replace( '/S(\d+)E(\d+)/', '\1x\2', $str );

Link on Codepad.

Upvotes: 1

Galen
Galen

Reputation: 30170

2 ways without regular expressions

$e = 'S05E14';
echo implode( 'x', explode( 'E', substr( $e, 1 ) ) );
echo str_replace( array( 'S', 'E' ), array( '', 'x' ), $e );

Upvotes: 0

anubhava
anubhava

Reputation: 785098

You can use:

$repl = preg_replace('/S(\d+)E(\d+)/i', '$1x$2', 'S05E14');

Code Demo

Upvotes: 3

Related Questions