Skip to content
Advertisement

remove part of string after delimiter in php

I have seen other I have a string " cccc cccc - fff"

I need to return "cccc cccc" I don’t need to delimiter too I tried to echo the result of substr($mystring , 0, strpos($mystring , "-")); but it return nothing I also tried

list($result, $trash) =split('-', $mystring);

 echo $result;
 echo $trash;

resulted returned the main string and trash resulted nothing

Update: i’m using wordpress and for some reason it is not working. I need to trim my title, i’m using get_the_title() and i’m trying to trim it

$mystring =get_the_title();

list($result, $trash) =split('-', $mystring); 
 echo $result;

Advertisement

Answer

After reading ShiraNai7’s comment, it seems you need a regex based solution. I’ve tested my pattern against your input as well as ShiraNai7’s different versions of the dash.

Pattern (Demo): /^ +K[w ]+(?= )/

Explanation:

  • / – start pattern
  • ^ – start match from start of the string
  • + – match one or more spaces characters (there is a literal space before the + sign)
  • K – disregard previously matched characters, start matching from this point.
  • [w ]+ – match one or more characters that are alpha-numeric, underscore, or space
  • (?= ) – a “positive lookahead” doesn’t capture what it matches; used to halt the match before final space that precedes delimiter (dash/hyphen/whatever)
  • / – end pattern

Method (Demo):

$my_string=" cccc cccc - fff";
$result=preg_match('/^ +K[w ]+(?= )/',$my_string,$out)?$out[0]:$my_string;  // if can't extract, use full string
echo $result;

Output:

cccc cccc

If this was my project, I would not be using regex, I would be using strstr() (again, just be sure you are using the appropriate hyphen character).

echo trim(strstr($my_string,'-',true));

strstr() with the “before_needle” (3rd parameter) set to true will return the substring that precedes the hyphen. Then simply trim() off the leading and trailing white-spaces.

Alternatively, explode is just as effective, it just generates an array before extracting the desired substring:

echo trim(explode('-',$my_string,2)[0]);  // don't bother generating more than one element - you only want the first anyhow
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement