Sarah
Sarah

Reputation: 415

how to trim string after specific word in php?

I want to trim a string after a specific word. Please check what I am doing:

$str = "kids-story-in-chaper2.php";
$rest = substr($str, 0, strpos($str, 'in'));

Here I am expecting output: -chapter2.php

But nothing work.

I want to trim after "in", I also tries

substr($str,11);        

// Working but the string is dynamic so I have to trim after "in". So its failed.

Any ideas or suggestions would be welcome.

Upvotes: 1

Views: 693

Answers (6)

Andreas
Andreas

Reputation: 23958

I usually avoid regex as much as possible but in this case I believe regex is the best option since it will not fail if the word "in" is missing in the string as the other solutions do.
The regex will grab anything that is after the $find and save it to the $match array.

$str = "kids-story-in-chaper2.php";
$find = "in";
preg_match("/". preg_quote($find) . "(.*)/", $str, $match);
if(isset($match[1])) echo $match[1];

https://3v4l.org/Blqua

Upvotes: 0

sradha
sradha

Reputation: 2244

Try this one

<?php
$str = "kids-story-in-chaper2.php";
echo $str = substr($str, strpos($str, 'in-')+3);

output you can check here

Upvotes: 1

shreyas d
shreyas d

Reputation: 774

$str = "kids-story-in-chaper2.php";
$rest = substr($str, strpos($str, 'in')+2);

Upvotes: 0

Maksym Fedorov
Maksym Fedorov

Reputation: 6456

You can find words and insert its position in substr function

$str = "kids-story-in-chaper2.php";
$separator = 'in';
$pos = strpos($str, $separator) + strlen($separator);
$rest = substr($str, $pos);

Upvotes: 1

Mdbw3
Mdbw3

Reputation: 1

Will this work for you?

$str = "kids-story-in-chaper2.php";
$rest = end(explode('-in', $str));

Upvotes: 0

Shobi
Shobi

Reputation: 11451

if you are sure that the string has only one -in- then you can you explode() the string. and take the last element using array_pop() or end().

$str = "kids-story-in-chaper2.php";
$res = explode('-in-', $str);
$res = array_pop($res);
echo $res;

//output
chapter2.php

Upvotes: 0

Related Questions