Remove portion of a string after a certain charact

2020-01-23 15:39发布

I'm just wondering how I could remove everything after a certain substring in PHP

ex:

Posted On April 6th By Some Dude

I'd like to have it so that it removes all the text including, and after, the sub string "By"

Thanks

标签: php string
15条回答
三岁会撩人
2楼-- · 2020-01-23 16:00

Austin's answer works for your example case.

More generally, you would do well to look into the regular expression functions when the substring you're splitting on may differ between strings:

$variable = preg_replace('/By.*/', '', $variable);
查看更多
放我归山
3楼-- · 2020-01-23 16:01

How about using explode:

$input = 'Posted On April 6th By Some Dude';
$result = explode(' By',$input);
return $result[0];

Advantages:

查看更多
聊天终结者
4楼-- · 2020-01-23 16:02

preg_replace offers one way:

$newText = preg_replace('/\bBy.*$/', '', $text);
查看更多
贼婆χ
5楼-- · 2020-01-23 16:02

By using regular expression: $string = preg_replace('/\s+By.*$/', '', $string)

查看更多
在下西门庆
6楼-- · 2020-01-23 16:03

You can use list and explode functions:

list($result) = explode("By", "Posted On April 6th By Some Dude", 2);
// $result is "Posted On April 6th "
查看更多
We Are One
7楼-- · 2020-01-23 16:05

Use the strstr function.

<?php
$myString = "Posted On April 6th By Some Dude";
$result = strstr($myString, 'By', true);

echo $result ;

The third parameter true tells the function to return everything before first occurrence of the second parameter.

查看更多
登录 后发表回答