1

I'm trying to figure out how to find a string in PHP then delete all cocurrent letters after that string has been found until an eventual space.

Essentially in my app, I have a big text mixed with everything. For my outputs I want to remove any words that BEGINS with the character '@'.

For example string:

This is a placeholder #string and it looks @great right?

How do I search this string and remove only the "@great" part? I will not know what the @xxx would be so I first need to search the string then replace it with nothing.

I understand I can do this:

<?php
$string = "This is a placeholder #string and it looks @great right?";
$newstring = str_replace("@great", "", $string);
print $newstring;
?>

But I will not know what the @xxx will contain or how long it will be. What I would know is there will be an eventual break/space and thats all I want to remove.

So if the text contains a "@", find it along with all cocurrent letters until a space then remove the "@xxx" until the space. Leave everything else in tact.

Any ideas?

Uz001
  • 11
  • 2

3 Answers3

2

You can use preg_replace.

This will find the @ symbol and remove all letters or numbers after it plus one space.

$string = "This is a placeholder #string and it looks @great right?";
$newstring = preg_replace("/@\w+\s/", "", $string);
print $newstring;

https://3v4l.org/OUe87

Andreas
  • 23,610
  • 6
  • 30
  • 62
-1

Method 1 combination of strpos() to locate the place in the original string and then substr() to return the string you want. Method 2 You an also use explode() and use @great as delimiter and then analyse the returned array to get what you want

Windkin
  • 63
  • 1
  • 4
  • 1
    You need to give more details. It does answer the question to some degree, but you could give an example – Andreas Nov 21 '17 at 14:56
-1

I found this : https://stackoverflow.com/a/5877136/8695939
Same question but with $.

\$(\w+)

Explanation :

\$ : escape the special $ character
() : capture matches in here (in most engines at least)
\w : match a - z, A - Z and 0 - 9 (and_)
+ : match it any number of times

Does it help ?

EDIT : With PHP preg-replace.

ThisIsJuke
  • 93
  • 12
  • Thanks it seems if I do \@(\w+) it can serve its purpose but how do I use regex in my context? In the context of find and replace? – Uz001 Nov 21 '17 at 15:02
  • Can I know why i have been downvoted ? I am here to help dudes.. I will edit my answer @Uz001 – ThisIsJuke Nov 21 '17 at 15:07