Pap
Pap

Reputation: 215

PHP remove and delete something after one special character

I have a very simple PHP question about replacing in string.

For example, our string is this :

This is a test - spam text

and i need to convert this string to this :

This is a test

I mean i want to detect the place of - charachter and delete everything after that.

How to do it ?

Upvotes: 2

Views: 206

Answers (4)

Sriraman
Sriraman

Reputation: 7937

One of the possible solutions:

$result = substr($str, 0, strpos($str, '-'));

Upvotes: 5

Charles
Charles

Reputation: 437

You can use Regular expressions to match anything after the - character.

This should work

/-.*/

When you match the string then you can replace the content using simple string functions.

Upvotes: 1

sfotiadis
sfotiadis

Reputation: 977

Try

$str = "This is a test - spam text";
$str = substr($str, 0, strpos( $str, '-'));

strpos() detects where - is.

Upvotes: 2

Thiago França
Thiago França

Reputation: 1847

use substr to return part of a string and strpos to find the position of the first occurrence of a substring in a string

$str = 'This is a test - spam text';

$newStr = substr($str, 0, strpos($str, '-'));
//               start ^  end ^

Upvotes: 2

Related Questions