preg_replace将drupal样式链接更改为标准标记

时间:2013-11-06 14:24:23

标签: php pattern-matching

我有内容说我正在从一个drupal站点迁移。我不确定这是否是标准drupal'功能',但所有标签都已转换为此格式:[link label](link url)

我试图将这些转换回preg_replace的普通链接,但成效有限。这是我目前的尝试:

$pattern = '/\[*\](.*?)/si';
$str = 'aving Accounts [Top Yields](http://www.topyields.nl/) - Share ';
$replacement = '<h1>';
echo preg_replace($pattern, $replacement, $subject, -1 );

(请忽略h1标签替换 - 显然这不是我用来创建链接标签的。

这给出了结果:

'aving Accounts [Top Yields<h1>(http://www.topyields.nl/) - Share'

我觉得我应该使用不同的功能来保留括号之间的内容,但搜索虽然php手册/ google / stackoverflow没有任何用处。

编辑(完整示例字符串):

'Welcome to the latest Edition of our Weekly Bulletin. Here we aim to provide our Subscribers and Clients with useful news, opinion and analysis in relation to macro-trends affecting the investment performance of real-assets and the general economy, ultimately facilitating well-informed investment decisions. In this bulletin we seek to provide you with a comparison of the three best money-market income investments, and one real-asset income investment. DGC Asset Management is a market-leading boutique providing Investors and Financial Advisors with access to market-leading Research Reports, and opportunities to invest in prime, productive property assets with a track record of generating annual yields exceeding 15%. By creating a credible point of reference, DGC aims to facilitate well-informed investment decisions amongst our Clients and Subscribers seeking to optimise and diversify investment portfolios with real-asset alternatives. ##A Comparison of the Best Income Investments in 2012## As most readers will be painfully aware, risk-free returns i.e. returns on insured cash deposits, remain ridiculously low as central banks continue to supress interest rates in an effort to stimulate economic growth (or offset economic contraction). In this Weekly Bulletin we analyse a range of traditional [income investments](/income-investments) and one DGC alternative, comparing the real-return (adjusted for inflation) and capital risk to a theoretical investment of £100,000 over 3 years This basic analysis is designed to offer Investors and Advisors with a simple comparison of the best of the best in terms of income investments. We have made a number of assumptions in our calculations, and all sources are referenced at the end of this page. This information should not be construed as financial advice or investment advice, and one should of course consult a Financial Advisor in order to ascertain the individual suitability of any given investment. ###Assumptions### **Capital invested:** £100,000 **Term:** 3 years **Tax rate:** 40% **Inflation:** 3.5% ###Best Savings Account### **Product:** Close Brothers 3-Year Fixed Rate Account **Gross Annual Rate:** 4% **After Tax:** 2.4% **After Tax and Inflation:** -1.06% **Real value after three years:** £96,845.36 **Real profit after 3 years:** -£3,154.64 **Risk**:- Up to £85,000 is insured under the FSCS, and Close Brothers are pretty stable, so risk to capital is minimal as you would rightly expect from an investment that generated a 'real' loss. ###Best Share Dividends### **Product:** Man Group Dividend **Gross Annual Rate:** 19.28% **After Tax:** 11.57% **After Tax and Inflation:** 7.8% **Real value after three years:** £125,262.55 **Real profit after 3 years:** £25,262.55 **Risk**:- As with any listed equity, Investors are exposed to the day to day vagaries of financial markets, and to the price performance of the underlying company. As we are measuring performance over a three year period, we should consider the volatility in the share price for the past three years, during which time Man Group's share price has fallen from 229.25 to 83.00, a variance of 63.8%. This simple analysis shows us that Investors who bought the stock three years ago have lost over half of their capital. ###Best Corporate Bond### **Product:** Enterprise Inns PLC Corporate Bond **Gross Annual Rate:** 10.45% **After Tax:** 6.27% **After Tax and Inflation:** 3.1% **Real value after three years:** £108,245.78 **Real profit after 3 years:** £8,245.78 **Risk**:- Just as with equities, the value of bonds will rise and fall based on the perceived stability of the issuing company. Again, we should consider the volatility in the share price for the past three years, during which time Enterprise Inns' share price has fallen from 137.75 to a low of 26.5 at the beginning of this year; a variance of 80.8%. Whilst this analysis provides some insight into company stability, we should really look at fluctuations in the traded value of the bond, which was originally issued with a coupon of 6.5%, and has fallen in value by around 50% since issue before rebounding somewhat. This level of volatility presents a significant risk to capital. Now, for good measure, we will also throw in our own 3-Year Exit Strategy Investment, based on the acquisition and short-term, leverage assisted disposal of heavily discounted high-yield property assets. ###Exit Strategy Investment### **Product:** Asset Backed 3-Year Property Investment **Gross Annual Rate:** 15% + 100% capital uplift after 3 years **After Tax:** 9% + 60% capital uplift after 3 years **After Tax and Inflation:** 5.5% + 54.12% capital uplift after 3 years **Real value after three years:** £170,920.76 **Real profit after 3 years:** £70,920.76 **Risk**:- Invested capital is secured directly against real-estate with an appraised (and disposal) value of circa. 200% of invested capital. Throughout the term of the investment (3 years), capital is always either secured against real-estate in this way, or held liquid in escrow, so the risk to capital is extremely low. However, Investors must be in a position to tolerate the potential illiquidity associated with property assets, although in this case properties are acquired and disposed of for a significant profit within a 30 day period, therefore we consider the risk profile of this product to be low to medium. ##Net Cash Profits After 3 Years Adjusted for Inflation## [](/user/login) ###Methodology### a) Gross Annual Rate: As advertised b) After Tax: Advertised rate less 40% c) After Tax and Inflation: After tax rate less 3.5% d) Real value after three years: ((100000 x B x B x B)/1.035/1.035/1.035) e) Real profit after 3 years: d - 100000 ###References### [This is Money](http://www.thisismoney.co.uk/money/saving/article-1621507/Best-saving-rates-Fixed-rate-bonds--accounts.html) - Saving Accounts [Top Yields](http://www.topyields.nl/) - Share Dividends [Investors Chronicle](http://stockcube.investorschronicle.co.uk/x/ic-bondtable2.html?groupid=GBPBonds&sort=7) - Corporate Bonds'

(对示例的冗长性质表示道歉 - 我觉得忽略任何事情可能会影响结果)

正如您所看到的,我目前正在将最终网址设置为第一个链接的网址

干杯!

2 个答案:

答案 0 :(得分:1)

the following能做你想做的吗?

<?php
   $pattern = '/\[([^]]*)\]\(([^\)]*)\)/si';
   $subject = <<<EOF
Text text text [LINK_1_TEXT](JUNK_LINK_1) - Share 
Text text text [LINK_2_TEXT](JUNK_LINK_2)
EOF;

   $replacement = '<a href="\2">\1</a>';

   echo "TEXT IS:\n" . $subject . "\n";
   echo "\nRESULT:\n";
   echo preg_replace($pattern, $replacement, $subject, -1 );
?>

输出以下内容:

TEXT IS:
Text text text [LINK_1_TEXT](JUNK_LINK_1) - Share 
Text text text [LINK_2_TEXT](JUNK_LINK_2)

RESULT:
Text text text <a href="JUNK_LINK_1">LINK_1_TEXT</a> - Share 
Text text text <a href="JUNK_LINK_2">LINK_2_TEXT</a>

正则表达式分解如下...... '/\[([^]]*)\]\(([^\)]*)\)/si';分成以下几个部分......

  1. \[([^]]*)\]第一部分与方括号匹配。你有这个 非常正确。括号被正确转义,以便它们 不被解释为范围。唯一的变化是使用[^]]* 而不是*。原始搜索零或更多[ 字符,更改搜索文字'['后跟零 或更多的字符(不是结束括号 - 否则你会得到同意的匹配*)后跟一个文字']'。

    .*周围的弯曲括号可以保存.*作为一组匹配的任何内容 - 称为capturing subpattern - 后来在替换字符串中将其称为“\ 1”。这称为back reference

  2. \(([^\)]*)\)这与包含文字的一组曲线括号相匹配。 ([^\)]*)创建第二个组,并在替换模式中称为\2[^\)]匹配任何不是)的字符。如果您使用.*,您将获得贪婪匹配

  3. 贪婪的比赛

    如果我使用字符串(This Text) blah [blah](blah) some more text

    \(.*\)匹配(This Text) blah [blah](blah)因为进行了贪婪的匹配...它会尽可能多地匹配字符串。

    如果你使用\([^\)]\),那么使用上面的示例字符串,它将匹配字符串中的模式两次,分别匹配This Text(blah)

答案 1 :(得分:1)

怎么样:

$pattern = '/\[(.*?)\]\((.*?)\)/';
$replacement = '<a href="\\2">\\1</a>';