【问题标题】:preg_replace to change drupal style links to standard a tagspreg_replace 将 drupal 样式链接更改为标准 a 标签
【发布时间】:2013-11-06 14:24:23
【问题描述】:

我有内容要从 drupal 站点迁移。我不确定这是否是标准的 drupal '功能',但所有 a 标签都已转换为这种格式:[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'

(对于示例的冗长性质表示歉意 - 我觉得省略任何内容可能会影响结果)

如您所见,我目前将最终 url 设置为第一个链接的 url

干杯!

【问题讨论】:

    标签: php pattern-matching


    【解决方案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[^\)] 匹配任何不是) 的字符。如果您使用.*,您将获得贪婪匹配

    贪婪匹配

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

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

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

    【讨论】:

    • 有些地方不太对劲 - 没有添加结束
    • 哦,在我的机器上工作...你得到什么输出?在ideone.com/ByicIb 上查看我的输出
    • 我认为这与在 url 位置有一个前导 / 因为该模式适用于我作为示例给出的 sn-p 但在此方面失败(例如:'寻找 @ 987654325@capab')
    • 抱歉反应慢 - 我得到这样的输出:traditional &lt;a href="http://stockcube.investorschronicle.co.uk/x/ic-bondtable2.html?groupid=GBPBonds&amp;sort=7"&gt;income investments](/income-investments) and one 在相对路径上(我很抱歉没有在我处理的问题中说清楚
    • 没问题。你能发送你正在测试的内容吗?我使用的正则表达式可能会有所改进....
    【解决方案2】:

    怎么样:

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

    【讨论】:

    • 不能对其他帖子发表评论,只能放 ? *s 之后可能会很好地解决您的问题。
    猜你喜欢
    • 2022-10-17
    • 1970-01-01
    • 2012-08-30
    • 1970-01-01
    • 2011-07-28
    • 1970-01-01
    • 2015-01-09
    • 1970-01-01
    • 2013-10-03
    相关资源
    最近更新 更多