user330840
user330840

Reputation: 11

Get leading part of a string and convert to kebab-case

I am trying to change title data into URL. I need to get rid off all text starting from "deadline" from the following dynamic data which I get from $title:

Examples:

I expect the results should be like this:

Here is the code I have tried

$newurl = strip_tags(str_replace("deadline","","$title"));
$code_entities_match = array( '&quot;' ,'!' ,'@' ,'#' ,'$' ,'%' ,'^' ,'&' ,'*' ,'(' ,')' ,'+' ,'{' ,'}' ,'|' ,':' ,'"' ,'<' ,'>' ,'?' ,'[' ,']' ,'' ,';' ,"'" ,',' ,'.' ,'_' ,'/' ,'*' ,'+' ,'~' ,'`' ,'=' ,' ' ,'---' ,'--','--');
$code_entities_replace = array('' ,'-' ,'-' ,'' ,'' ,'' ,'-' ,'-' ,'' ,'' ,'' ,'' ,'' ,'' ,'' ,'-' ,'' ,'' ,'' ,'' ,'' ,'' ,'' ,'' ,'' ,'-' ,'' ,'-' ,'-' ,'' ,'' ,'' ,'' ,'' ,'-' ,'-' ,'-','-');
$newtitle = str_replace($code_entities_match, $code_entities_replace, $newurl);
$urltitle = strtolower($newtitle);

Unfortunately, the results are:

Upvotes: 1

Views: 398

Answers (3)

mickmackusa
mickmackusa

Reputation: 47874

To produce the desired kebab-case string from your US state lead inout strings:

  1. Isolate the substring before the space and "deadline",
  2. Convert any spaces to hyphens, then
  3. Cast all letters to lowercase

Code: (Demo)

echo strtolower(
         strtr(
             strstr($str, ' deadline', true),
             ' ',
             '-'
         )
     );

If your input might contain consecutive spaces, hyphens, or other symbols, the implementation would need more intricate handling

Upvotes: 0

Galen
Galen

Reputation: 30170

Here's a non-regex way

$str = 'New York deadline May 14th, 2010 (urgent)';
$title = str_replace( ' ', '-', current( explode( ' deadline', $str ) ) );

Upvotes: 2

codaddict
codaddict

Reputation: 454950

You can use preg_replace as:

$str = 'New York deadline May 14th, 2010 (urgent)';

$to = array('/deadline.*/','/^\s+|\s+$/','/\s+/');
$from = array('','','-');
$str = strtolower(preg_replace($to,$from,$str));

echo $str; // prints new-york

Upvotes: 2

Related Questions