1

I'm looking for a regex to find words in string starting with # and not have any more repeated #

Given:

Hi I'm #hany #هانى my Friend #john#john is ##here . good bye#all .

I want the final result as this:

Hi I'm <a>#hany</a> <a>#هانى</a> my Friend #john#john is ##here . good bye#all .

I'm using this:

echo preg_replace('/(?!\b)#(\\S+)/','<a>$0</a>',$string);

I want only words starting with # and not have any more hashes like twitter hash-tags.

4

2 回答 2

3

试试这个模式:

echo preg_replace('/(?<=\s)(#[^#\s]+)(?=\s)/', '<a>$0</a>' ,$string);

输出:

Hi I'm <a>#hany</a> <a>#هانى</a> my Friend #john#john is ##here . good bye#all .
于 2013-07-21T00:04:44.717 回答
0

试试这个:

echo preg_replace('~(?<=\s|^)#[^\s#]++~um', '<a>$0</a>', $string);

说明:

~             # pattern delimiter (instead of /, but it's the same)
(?<=          # open a lookbehind (means "preceded by")
    \s | ^    # a white character (space, tab, newline...) or the begining of the line
)             # close the lookbehind
#             # literal #
[^\s#]++      # all that is not a # or a white character, one or more times (possessive)
~             # delimiter
um            # u for unicode string, m for multiline mode
于 2013-07-21T00:04:51.000 回答