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

JavaScript

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

JavaScript

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):

JavaScript

Output:

JavaScript

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).

JavaScript

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:

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement