I am trying to ensure that a slug formatted string is within the total character limit by removing words from the middle of the string if warranted.
Sample slug:
'/job/hello-this-is-my-job-posting-for-a-daycare-im-looking-for-in-91770-rosemead-california-12345'
The string will always start with /job/ and end with in-zipcode-city-state-job_id. However, there is a 150 character limit to the slug and I am looking to truncate words before the zipcode one at a time so this character limit is not exceeded. I know I have to use regex/explode, but how can I do this? I tried the following but my matches array seems to have too many elements.
$pattern = '/-in-\d{5}-(.*)-(.*)-(\d*)/';
$string = '/job/hello-this-is-my-job-posting-for-a-daycare-im-looking-for-in-91770-rosemead-california-12345';
preg_match($pattern, $string, $matches);
print_r($matches);
// Array
(
[0] => -in-91770-rosemead-california-12345
[1] => rosemead
[2] => california
[3] => 12345
)
Why is rosemead, california, 12345 considered matches? Shouldn't there only be the first element?
How do I ensure that the complete slug will be a maximum of 150 characters long, with the trailing part (location) included in its entirety, and the leading part (job name) truncated if necessary?
You can do this without using
explode()and iterating, just with some standard string manipulation: