jmenezes
jmenezes

Reputation: 1926

Detecting beginning of line and end of line in preg_replace

$data = $_POST['data'];

echo '<form method="post"><textarea name="data"></textarea><input type="submit">';

echo preg_replace( "#/*[?+]/n#", "[h1]$1[/h1]",$str );

Is it possible with preg_replace to detect the beginning of a line and apply a certain html code to the entire line based on a few characters at the beginning of it?

Here, based on the * if the data were:

*This is row one
//output <h1>This is row one</h1>

**This is row two
//output <h2>This is row two</h2>

***This is row three
//output <h3>This is row three</h3>

***This is row * three
//output <h3>This is row * three</h3>

This is row * three
//output This is row * three

I'm having troble detecting the begining of the line and end of the line and wrapping tags around the text in the line.

I don't need any * in between the line matched. My failed effors are included. Can you help?

Upvotes: 0

Views: 2471

Answers (2)

anubhava
anubhava

Reputation: 785098

Code:

$str = "*This is row one\n**This is row two\n***This is row three\n***This is row * three\nThis is row * three"; 
 
$result = preg_replace('/^\*([^*].*)$/m', '<h1>$1</h1>', $str);

$result = preg_replace('/^\*{2}([^*].*)$/m', '<h2>$1</h2>', $str);

$result = preg_replace('/^\*{3}([^*].*)$/m', '<h2>$1</h2>', $str);

Upvotes: 1

i alarmed alien
i alarmed alien

Reputation: 9520

See http://www.regular-expressions.info/anchors.html for full details

// replace *** with h3
$str = preg_replace('/^\*{3}([^\*].*)$/', '<h3>$1</h3>', $str);

// replace ** with h2
$str = preg_replace('/^\*{2}([^\*].*)$/', '<h2>$1</h2>', $str);

// replace * with h1
$str = preg_replace('/^\*([^\*].*)$/', '<h1>$1</h1>', $str);

Explanation: * is a special character in regular expressions, so it has to be escaped, like so: \*.

^\* searches for * at the beginning of the string. [^\*] searches for anything that is NOT * -- the square brackets are used to search for a class of characters, and the ^ means 'NOT'. Therefore, to search for *** without also matching ****, we use the expression /^\*{3}[^\*]/.

Upvotes: 2

Related Questions