Jump to content

Replacing&extracting an item in a string


Shadowing

Recommended Posts

Hey guys i think i must be missing something. Trying to do this with less code possible

 

Was looking over string functions in the manual but i dont see anything that does what im trying to do.

 

$string = "hey whats up @sam how are you doing";

 

I'm wanting to replace @sam with

<a href='' class='profile_name' id='$name>$name</a>

 

is there a way to extract @sam so i can get rid of the @ then place the name into the link $name

 

the only thing i can find is finding the location of @ using strpos but im not sure how to extract only the letters attached to @ and nothing else in the string

 

 

only way i can think about doing it is to extract everything after @ then exploding it by spaces with a limit of 1

is that the best way to do this?

Link to comment
https://forums.phpfreaks.com/topic/266392-replacingextracting-an-item-in-a-string/
Share on other sites

Try using a regular expression to match the at symbol followed by any characters [edit: plural] that aren't a space followed by a space:

/@([^\s]+)\s/

Use this with a function like preg_match to find the name. Note that the brackets around the part between the @ and the following space indicate a part you wish to save for use.

thanks for the responce Tarential

 

expressions are like a dark art to me lol

Thanks alot it works.

i'll go ahead and just submit my code incase someone else reads this to help them out.

 

$string = "hey whats up @sam how are you doing";

if (preg_match('/@([^\s]+)\s/', $string, $name)) { 	

	print_r($name);

}

Either use regular expression or use the str_replace() function.  That takes a search term, a replacements term and the string you want to work on.

 

I've heard it's quicker than using preg_replace with regex but it's probably such a nominal difference that it's not worth worrying about.

 

:)

Either use regular expression or use the str_replace() function.  That takes a search term, a replacements term and the string you want to work on.

 

I've heard it's quicker than using preg_replace with regex but it's probably such a nominal difference that it's not worth worrying about.

 

:)

 

The difference in speed is huge, but str_replace will only match static data. Regular expressions allow for patterns to be found.

Ahh well there you go :)

 

And yeah I would favour regex if looking for something dynamic but the post seemed to suggest @sam was the term - so maybe i misread :)

 

Either use regular expression or use the str_replace() function.  That takes a search term, a replacements term and the string you want to work on.

 

I've heard it's quicker than using preg_replace with regex but it's probably such a nominal difference that it's not worth worrying about.

 

:)

 

The difference in speed is huge, but str_replace will only match static data. Regular expressions allow for patterns to be found.

ya the name is dynamtic

 

im confused on how i would use preg_replace. How would i get the variable $name filled in this link with sam using preg_replace instead of preg_match? You saying this could be done in one line of code xyph?

<a href='' class='profile_name' id='$name>$name</a>

$string = "hey whats up @sam how are you doing";

if (preg_match('/@([^\s]+)\s/', $_POST['message'], $name)) { 	

	print_r($name);

}

Probably not the most efficient way of doing it but it works...

 


$string = "hey whats up @sam how are you doing";

$pattern = '/@[a-zA-Z]+/';

 preg_match($pattern, $string, $matches);

$name =  substr($matches[0], 1);



$stringtwo = "<a href='' class='profile_name' id='name'>$name</a>";


//$string contains new string with link changed to name dynamically
$string = str_replace($matches[0], $stringtwo, $string);

Just need to change the pattern to:

 

'/\s@[a-zA-Z]+/';

 

Oh and add a space before $name in $stringtwo

 

$stringtwo = "<a href='' class='profile_name' id='name'> $name</a>";

 

how would i go about changing it so its looking for "  @" instead of "@"

 

this way people can still type email address's and it will ignore it

Adding "\s" in front of the @ symbol in the regex is the correct way to include a space in the match. Then, assuming you used my code, you would reference $matches[1] (not $matches as a whole, which is an array, or $matches[0], which is the entire string match). $matches[1] is what contains "sam" in the array you posted.

The manual provides details on how to do this is preg_replace. I'm not sure why I need to post an example as well.

 

Also \s is the correct way to match a white-space character. A literal space, or one preceded by a backslash in the case of free-spacing, is the correct way to match a space.

 

<?php

$string = 'hello @sam nice to meet you';

$match = '/@([^\s]+)/';
$replace = '<a href="page.php?name=$1">$1</a>';

echo preg_replace($match, $replace, $string);

?>

Tarential: No need to bind the RegExp to the start and end of the string. We're not talking about validating the entire string, but just looking to grab a little subset of it. ;)

 

Shadowing: To sum up this little thread, what you'll need is something that looks like this:

$string = "hey what's up @sam how are you doing?";
$replace = ' <a href="" class="profile_name" id="$1">$1</a>';
echo preg_replace ("/\\s@(\\S+)/u", $replace, $string);

 

Double escaping since "\" is a meta-character in PHP strings. "\\S" is the same as "[^\\s]+", only with less typing. Also using the "u" modifier to make it UTF-8 compatible. Also, added a space in front of the anchor-tag, to replace the one we're removing in the RegExp. ;)

Tarential: No need to bind the RegExp to the start and end of the string. We're not talking about validating the entire string, but just looking to grab a little subset of it. ;)

 

Shadowing: To sum up this little thread, what you'll need is something that looks like this:

$string = "hey what's up @sam how are you doing?";
$replace = ' <a href="" class="profile_name" id="$1">$1</a>'
echo preg_replace ("/\\s@(\\S+)/u", $string, $replace);

 

Double escaping since \ is a meta-character in PHP strings. "\\S" is the same as "[^\\s]+", only with less typing. Also using the "u" modifier to make it UTF-8 compatible.

 

You should test your code.

Out of interest so i understand this patttern (as my regex is a bit rusty):

 

$match = '/@([^\s]+)/';

 

This pattern says:  find instance of '@' then match anything that isn't a space after the @? Tis very clever if that's the case - regex really is quite something.

Yep, that's exactly what it says. With the added bit of storing that "everything that isn't a space" in a sub group, which is then referenced to by the "$1" in the replacement string.

 

RegExp sure is great, but easily abused and can get really complex really fast. So take heed when using it. ;)

Yeah, noticed it right after posting. Changed it while you were posting. :P

 

What about

$string = "@sam loves po-ta-toes";

 

Out of interest so i understand this patttern (as my regex is a bit rusty):

 

$match = '/@([^\s]+)/';

 

This pattern says:  find instance of '@' then match anything that isn't a space after the @? Tis very clever if that's the case - regex really is quite something.

 

You've got it. The + means 1 or more times, and the brackets capture the result to be used later.

 

So, it has to be an @ followed by one or more characters than aren't spaces.

What about

$string = "@sam loves po-ta-toes";

 

Seems we both missed out on something: :P

how would i go about changing it so its looking for "  @" instead of "@"

 

this way people can still type email address's and it will ignore it

 

Though, I should indeed have thought about the possibility of the search term being the first word in the string. I shall fix that right away. :)

 

Addendum:

Hmm.... Seems I can't go back and edit my post any more. Oh, well. Here's the updated version:

$string = "@Christian is testing!";
$replace = '$1<a href="" class="profile_name" id="$2">$2</a>';
echo preg_replace ("/((?<!\\S))@(\\S+)/u", $replace, $string);

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.