0

The problem I'm encountering with this is if I have single characters in the array $wordstodelete it then deletes them from words in the $oneBigDescription.

$oneBigDescription = str_replace ( $wordstodelete, '', $oneBigDescription);

So it makes it look like this:

array (size=51)
  'blck' => int 5
  'centrl' => int 6
  'clssc' => int 6
  'club' => int 10
  'crs' => int 54
  'deler' => int 7
  'delers' => int 5
  'engl' => int 6
  'felne' => int 8
  'gude' => int 5
  'hot' => int 5
  'jgur' => int 172
  'jgurs' => int 5
  'lke' => int 6

Is there a way to only delete the single character from $oneBigDescription if it is on its own?

1
  • 3
    I'm having a hard time understanding your request. Can you show an example that describes what your problem is and what you need? Commented Jul 21, 2012 at 12:52

3 Answers 3

2

$oneBigDescription = preg_replace("/\b$wordstodelete\b/", '', $oneBigDescription);

/b should look for word boundaries to ensure it's an isolated word when one character is used.

EDIT: Didn't quite read that right - this is more assuming you're looping over $wordstodelete as an array of words.

So, something like this:

$desc = "blah blah a b blah";
$wordstodelete = array("a", "b");
foreach($wordstodelete as $delete)
{
    $desc= preg_replace("/\b$delete\b/", "", $desc);
}

EDIT2: Wasn't quite happy with this, so refined slightly:

$arr = "a delete aaa a b me b";
$wordstodelete = array("a", "b");
$regex = array();
foreach($wordstodelete as $word)
{
    $regex[] = "/\b$word\b\s?/";
}
$arr = preg_replace($regex, '', $arr);

This account for taking out the following space, which in HTML isn't usually an issue when rendered (since consecutive spaces aren't generally rendered), but still a good idea to take it out. This also creates an array of regex expressions up front, which seems a bit nicer.

Sign up to request clarification or add additional context in comments.

Comments

0

It sounds like you might need to use a little regex

$oneBigDescription = preg_replace('/\sa\s/', ' ', $oneBigDescription);

This will take "Black a central" and return "Black central"

Comments

0

you can use preg_replace to replace only "words on its own" like the following: (I'm generating the regular expressions so the list of words can stay the same)

$wordsToReplace = ("a", "foo", "bar", "baz");
$regexs = array();
foreach ($wordsToReplace as $word) {

    $regexs[] = "/(\s?)". $word . "\s?/";
}

$oneBigDescription = preg_replace($regexs, '\1', $oneBigDescription);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.