/    Sign up×
Community /Pin to ProfileBookmark

preg_replace matching word with inner tag

Say you have a string:

[code=php]
$str=’This is a<wbr /> line of te<wbr />xt’;
[/code]

I want to wrap certain words with a span tag, like:

[code=php]
preg_replace(‘/text/’,'<span>$1</span>’,$str);
[/code]

But obviously that doesnt work because in the string there is a ‘<wbr />’ in the middle of it. Note that I can’t strip out the ‘<wbr />’.

Does anyone know how I would go about doing this?

Many thanks!

to post a comment
PHP

3 Comments(s)

Copy linkTweet thisAlerts:
@artemisauthorAug 23.2007 — By the way, it's worth pointing out that there won't necessarily be a '<wbr />' in the middle of the word and the location of it is arbitrary.. e.g.

[code=php]
$str='This is a<wbr /> line of te<wbr />xt, look at this text and how good this tex<wbr />t is.';
[/code]


Also there could be more than one, such as:

[code=php]
$str='t<wbr />e<wbr />xt';
[/code]
Copy linkTweet thisAlerts:
@artemisauthorAug 23.2007 — Nevermind, after a phat amount of regexing i figured it out
Copy linkTweet thisAlerts:
@yannyannyannFeb 18.2011 — hi i would be very interested in your olution if you still remember it.

I have this as an input:

<p>Hello wo<em>rld</em></p>

<p>How are you <span style='text-decoration:underline'>doing?</span></p>

i need to have the following output:

<p><span id='w_1'>Hello</span> <span id='w_2'>wo<em>rld</em></span></p>

<p><span id='w_3'>How</span> <span id='w_4'>are</span> <span id='w_5'>you</span> <span id='w_6'><span style='text-decoration:underline'>doing?</span></span></p>


thanks in advance !
×

Success!

Help @artemis spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.18,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...