Home > Software engineering >  Create a function to find a specific word in the title
Create a function to find a specific word in the title

Time:06-25

I have the following title formation on my website:

It's no use going back to yesterday, because at that time I was... Lewis Carroll

Always is: The phrase… (author).

I want to delete everything after the ellipsis (…), leaving only the sentence as the title. I thought of creating a function in php that would take the parts of the titles, throw them in an array and then I would work each part, identifying the only pattern I have in the title, which is the ellipsis… and then delete everything. But when I do that, in the X space of my array, it returns the following:

was...

In position 8 of the array comes the word and the ellipsis and I don't know how to find a pattern to delete the author of the title, my pattern was the ellipsis. Any idea?

<?php
$a = get_the_title(155571);
$search = '... ';
if(preg_match("/{$search}/i", $a)) {
    echo 'true';
}
?>

I tried with the code above and found the ellipsis, but I needed to bring it into an array to delete the part I need. I tried something like this:

<?php
define('WP_USE_THEMES', false);
require('./wp-blog-header.php');
global $wpdb;

$title_array = explode(' ', get_the_title(155571));
$search = '... ';
if (array_key_exists("/{$search}/i",$title_array)) {
echo "true";
}
?>

I started doing it this way, but it doesn't work, any ideas?

Thanks,

CodePudding user response:

If you use regex you need to escape the string as preg_quote() would do, because a dot belongs to the pattern.

But in your simple case, I would not use a regex and just search for the three dots from the end of the string.

Note: When the elipsis come from the browser, there's no way to detect in PHP.

$title = 'The phrase... (author).';
echo getPlainTitle($title);

function getPlainTitle(string $title) {
    $rpos = strrpos($title, '...');
    return ($rpos === false) ? $title : substr($title, 0, $rpos);
}

will output

The phrase

CodePudding user response:

First of all, since you're working with regular expressions, you need to remember that . has a special meaning there: it means "any character". So /... / just means "any three characters followed by a space", which isn't what you want. To match a literal . you need to escape it as \.

Secondly, rather than searching or splitting, you could achieve what you want by replacing part of the string. For instance, you could find everything after the ellipsis, and replace it with an empty string. To do that you want a pattern of "dot dot dot followed by anything", where "anything" is spelled .*, so \.\.\..*

$title = preg_replace('/\.\.\..*/', '', $title);
  •  Tags:  
  • php
  • Related