开发者

Replacing all parts in a string wrapped with ** signs like so ** with a string?

I was looking at mimicking functionality that is used here at stackoverflow with the double asterisk.

Say you have a variable like so:

$string = 'hello i am **a string** and开发者_如何学C i have **stuff in me**';

And I wanted to go through this string and replace anything that is wrapped in double asterisks (**) with something else. In my situation, its to make everything wrapped in those asterisks with a link.

i.e.

$link = 'http://www.something.com';

The end result of $string would look like so:

$string = 'hello i am <a href="http://www.something.com">a string</a> and i have <a href="http://www.something.com">stuff in me</a>';

How does one do something like this?


$newString = preg_replace(
    '/\*\*(.*?)\*\*/',
    '<a href="http://www.something.com/">$1</a>',
    $string
);

To explain, the pattern matches a double asterisk, followed by anything up to the next double asterisk, capturing the "anything" in a group.

The replacement then refers to this group using the $1


Try out regular expressions

echo preg_replace('/\*\*(.*?)\*\*/','<a href="http://www.google.com">${1}</a>',$your_string);


Instead of doing it yourself, why not simply use the PHP Markdown library? I have used it myself and it is quite easy. Pair it with the Javascrip-based Markdown preview used here on StackOverflow (link) and you're all set!


Here's a quick and dirty answer:

$string = 'hello i am **a string** and i have **stuff in me** and here **is some more**';
$string_parts = explode( '**', $string );
$final_string = '';
$wraps[0] = '<a href="http://www.something.com">';
$wraps[1] = '</a>';
$x = 0;
foreach( $string_parts as $index => $string_part ){
    if( $index == count($string_parts) - 1 ){
        break;
    }
    $final_string .= $string_part . $wraps[$x];
    $x++;
    if( $x > 1 ){
        $x = 0;
    }
}
echo $final_string;

It's not pretty, but it works.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜