0

I've searched around here about this topic, suggestions that i saw are from topics like

Check if a character is a word boundary

but i don't know if that's what i need exactly

My problem is this, I have to extract a string from word which can be a single character but also can be multiple, in this question I'm only discussing single character because that's the main problem in my situation, other types where string is multiple characters is easily identifiable because there's only one encounter for it in the string where I'm removing it from

"S Shoulder Pads"

In this example i have to remove character S from this string, problem is data is not really consistent, So strpos() or strrpos() don't always work. this same string can be provided reversed and because of this i can't consistently know where my needed character is located at

"Shoulder Pads S"

My only validation for the single character string that i need to extract is, if character is a single letter and it's not a part of any word in this example S then it's valid for removal. is there some nice way of doing this in PHP?

5
  • 2
    Preg_replace and regex word boundaries?
    – nice_dev
    Commented Jul 7, 2020 at 15:26
  • thanks for the help, do i understand correctly that regex word boundaries is used to determine if a specific string starts/ends a string Commented Jul 7, 2020 at 15:32
  • They make sure a string is not surrounded by any other word character.
    – nice_dev
    Commented Jul 7, 2020 at 15:33
  • 1
    A better explanation with wording stackoverflow.com/questions/1324676/…).
    – nice_dev
    Commented Jul 7, 2020 at 15:35
  • 1
    if get it correctly something like this "\bS\b" would work in my case, (quick test on regexr) Commented Jul 7, 2020 at 15:37

1 Answer 1

2

As you have guessed it correctly, you can use a word boundary \b around your string to match it in such a way that it exists individually and not as a part of any string. You can use preg_replace to replace the matched string with any string, which is the second parameter for this function.

Snippet:

<?php

$tests = [
        "S Shoulder Pads",
        "Shoulder Pads S",
        "SSSSS S S S"
    ];

foreach($tests as $test){
    echo preg_replace('/\bS\b/','',$test),PHP_EOL;
}
1
  • 1
    Thanks for the explanation, i just discovered the same solution as well Commented Jul 7, 2020 at 15:43

Not the answer you're looking for? Browse other questions tagged or ask your own question.