Ivan Topić
Ivan Topić

Reputation: 3185

Get string up to character using regex

These are examples of my strings:

My title - K21
Some title  - G-21
Title something - M-02

I need to strip the code and the hyphen so I get clear title.

My title
Some title
Title something

This is the code I came up so far, but it gives me G-21 as result, and I need the opposite, I need a result of regular expression.

$string = 'Some title - G-21';
$pattern = '/.+? (?=–)/i'; // this is ok, &#8211 is for '-'
echo preg_replace($pattern, '', $string);

Upvotes: 0

Views: 71

Answers (3)

RomanPerekhrest
RomanPerekhrest

Reputation: 92884

Use the following regex pattern for multiple substrings:

$str = "My title - K21
Some title  - G-21
Title something - M-02";

$result = preg_replace("/-\s+[A-Z]-?\d+/", "", $str);

print_r($result);

The output:

My title 
Some title  
Title something 

Upvotes: 1

jmcgriz
jmcgriz

Reputation: 3368

Two ways to look at this one. The first direct answer to your question is to use preg_match instead of preg_replace.

The second way to look at it is to use your current preg_replace syntax to strip off the end of the strings. Something like /\s+-.+$/ should work for stripping off the hyphen and everything after it

Upvotes: 0

Sean Bright
Sean Bright

Reputation: 120704

Do you have to use a regular expressions?

<?php
$str = 'Some title  - G-21';
$res = trim(array_shift(explode("&#8211;", $str, 2)));

echo $res;
?>

Upvotes: 2

Related Questions