I have my working code which extracts the title from a string, but right now it still isn't very flexible.
Current code:
$post_title = "THIS IS A TEST - 10-01-2010 - HELLO WORLD (OKAY)!!";
$post_title = substr($post_title, 0, strpos($post_title, '-') - 1);
I want to get the title of the string, which is at the start of the string and goes until the first dash. I don't want to get the spaces before the dash and it could be that there is no dash at all.
The output of the current code works and outputs THIS IS A TEST
, but the current code doesn't work for the following cases, so I need a more flexible code:
- THIS IS A TEST - 10-01-2010 - HELLO WORLD (OKAY)!!
- THIS IS A TEST-10-01-2010 - HELLO WORLD (OKAY)!!
- THIS IS A TEST - - - - 10-01-2010 - HELLO WORLD (OKAY)!!
- THIS IS A TEST
So the title can exist without a -
and someone could forget to put a space between the -
, equally, someone could put too many spaces.
The output for all the above cases should always be THIS IS A TEST
with no spaces at the end.
With the code I have, the only one that works is the first one.
$title= explode('-', $post_title);
$post_title=trim($title[0]);
$trimmedTitle=$post_title;
$str = "THIS IS A TEST -0-01-2010 - HELLO WORLD (OKAY)!!";
preg_match("/^([\w\s]+)\s*-?/m", $str, $m);
print_r($m);
if(strpos($string,'$post_title')){echo explode('$post_title',$string)[0];}
I mught have failed to mention that$post_title'
is the title of the wordpress post, thus it will change depending on the post. Thank you, I am testing it now.THIS IS A TES