/    Sign up×
Community /Pin to ProfileBookmark

help with regular expression would be welcomed

Hello

I am quite new to regular expression and I am faced with a challange that I feel could be solved quite easily using regular expression.
I would appreciate if someone could help me with the solution and if possible to explain how he/she solved it so I will pick up my regular expression knowledge.

Here is the problem:
I am given a PHP string like so:
$phrase = ‘Jo?n* Mil??er’
Where *
means zero or more occurances of any letter ([b]except whitespace[/b])
and ? means a single occurance of any letter ([b]except whitespace[/b])

I then get another sentence (in another PHP string) in which the phrase was found. For example: ‘Johnny Miller was here’
I need to use regular expressions to highlight the phrase in the sentence (using the <b> tag).

So in the example above, the highlighted expression will be:
‘<b>Johnny Miller</b> was here’

Here is another example:
$phrase = ‘*a*
$sentence = ‘The tall man walked down the street’
The highlighted sentecne will be:
‘The <b>tall</b> <b>man</b> <b>walked</b> down the street”
or in HTML:
‘The [b]tall[/b] [b]man[/b] [b]walked[/b] down the street’
I would appreciate any help
regards
Jason

to post a comment
PHP

1 Comments(s)

Copy linkTweet thisAlerts:
@phpnoviceDec 31.2004 — Perhaps something like this:
[code=php]<?php
function boldIt($str, $sel) {
$sel = preg_replace('/\?/i', '\S', $sel);
$sel = preg_replace('/\*/i', '\S*', $sel);
$str = preg_replace("/({$sel})/i", '<b>$1</b>', $str);
return $str;
}

$str = "<p>The tall man walked down the beach.</p>";
echo boldIt($str, '*a*');

$str = "<p>The boy, Johnny Miller, was here.</p>";
echo boldIt($str, 'Jo?n* Mil*er');
?>
[/code]
×

Success!

Help @jasongr 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.27,
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,
)...